File size: 288,929 Bytes
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
3331871
 
 
 
 
 
 
 
 
 
9e15897
c72f0a1
83f1a82
a83fcff
3331871
a83fcff
affe37f
d598032
 
8145bee
b2aa446
aa1490a
a83fcff
3331871
b2aa446
c72f0a1
 
3331871
 
 
b80130d
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
cf09724
2e77cd4
3331871
affe37f
3331871
 
affe37f
3331871
 
 
 
 
 
39a9177
 
 
 
 
 
3331871
 
affe37f
3331871
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06aad61
 
 
 
 
 
 
e13472e
06aad61
e13472e
06aad61
 
 
e13472e
06aad61
e13472e
06aad61
 
e13472e
06aad61
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
 
 
3331871
 
06aad61
3331871
 
 
 
 
 
 
 
e13472e
3331871
 
 
 
1ad1eea
3331871
a83fcff
affe37f
c72f0a1
 
 
e13472e
 
1ad1eea
7f72224
85f794d
3331871
 
 
 
 
 
06aad61
3331871
 
06aad61
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
3331871
 
 
 
 
 
 
 
 
affe37f
1ad1eea
 
 
3331871
 
affe37f
 
a83fcff
affe37f
81a8217
c72f0a1
 
 
e13472e
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
1ad1eea
 
7f72224
85f794d
 
3331871
affe37f
 
 
 
 
 
 
 
 
3331871
bdac669
 
 
 
ce4ad7b
 
 
 
affe37f
ce4ad7b
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
 
b2aa446
 
3331871
affe37f
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcd43e2
1ad1eea
 
dcd43e2
 
 
 
 
 
 
 
 
 
 
1ad1eea
3331871
 
 
 
 
39a9177
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
e13472e
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
ce4ad7b
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
affe37f
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
7f72224
 
 
 
3331871
 
 
 
7f72224
3331871
 
 
 
e13472e
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
3331871
 
 
e13472e
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
cf09724
b2aa446
 
 
 
 
 
3331871
 
 
cf09724
b2aa446
3331871
 
affe37f
 
 
3331871
affe37f
 
 
 
 
 
3331871
affe37f
 
3331871
affe37f
3331871
affe37f
3331871
 
 
affe37f
3331871
affe37f
 
 
 
3331871
affe37f
 
3331871
 
 
 
 
 
 
1ad1eea
3331871
 
 
1ad1eea
3331871
 
 
1ad1eea
 
 
 
 
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
affe37f
3331871
 
 
 
 
affe37f
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
affe37f
3331871
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
affe37f
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
f45c4c2
3331871
 
affe37f
3331871
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
affe37f
3331871
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
affe37f
3331871
 
 
affe37f
3331871
 
 
 
 
affe37f
3331871
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
affe37f
3331871
 
 
c72f0a1
 
 
 
3331871
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
3331871
 
 
e13472e
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
3331871
 
 
 
 
7f72224
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e77cd4
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e77cd4
3331871
 
 
affe37f
3331871
 
 
2e77cd4
 
 
 
 
 
 
 
 
 
3331871
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
3331871
 
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
affe37f
3331871
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
3331871
 
 
 
 
 
 
 
e13472e
3331871
 
e13472e
3331871
e13472e
 
 
 
 
 
 
3331871
 
e13472e
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
e13472e
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
b80130d
 
 
 
 
3331871
b80130d
3331871
 
 
 
1ad1eea
 
3331871
1ad1eea
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
3331871
 
85f794d
 
 
 
ce4ad7b
3331871
 
ce4ad7b
3331871
ce4ad7b
3331871
ce4ad7b
3331871
ce4ad7b
85f794d
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e13472e
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
e13472e
3331871
 
 
 
 
 
d598032
 
 
 
 
 
 
 
affe37f
3331871
affe37f
 
e13472e
 
 
3331871
 
 
 
 
 
 
 
 
 
affe37f
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
 
3331871
b80130d
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
affe37f
dc31bad
3331871
 
 
 
cf09724
3331871
 
 
 
 
 
 
39a9177
 
 
 
 
85f794d
 
 
 
 
39a9177
 
 
c72f0a1
39a9177
affe37f
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
3331871
 
 
 
ce4ad7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
 
3331871
 
 
85f794d
 
3331871
 
 
 
 
 
 
 
 
 
 
ce4ad7b
 
 
 
3331871
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf09724
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b80130d
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
 
 
 
 
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
39a9177
 
 
 
a83fcff
affe37f
39a9177
cf09724
b2aa446
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
 
 
39a9177
affe37f
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
affe37f
39a9177
affe37f
 
39a9177
 
 
 
 
 
 
 
 
c72f0a1
39a9177
 
 
 
 
c72f0a1
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
39a9177
 
 
 
 
c72f0a1
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0aaeea7
39a9177
0aaeea7
39a9177
 
 
 
 
 
 
 
 
c72f0a1
39a9177
 
81a8217
 
39a9177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
a83fcff
85f794d
8145bee
7f72224
c72f0a1
83f1a82
8145bee
 
a83fcff
 
 
 
 
 
 
 
 
 
aa1490a
 
 
a83fcff
 
 
 
 
8145bee
a83fcff
 
 
 
 
 
1ad1eea
 
 
a83fcff
1ad1eea
a83fcff
 
 
 
 
aa1490a
 
a83fcff
 
 
aa1490a
a83fcff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ad1eea
 
aa1490a
8145bee
a83fcff
 
 
 
 
 
 
 
 
1ad1eea
a83fcff
 
 
9e15897
a83fcff
 
 
 
 
 
 
 
d598032
a83fcff
 
 
 
 
 
 
 
 
d598032
a83fcff
 
 
 
 
 
 
 
 
 
071ce2b
 
 
 
a83fcff
 
aa1490a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d598032
 
affe37f
aa1490a
8145bee
 
 
 
 
 
aa1490a
8145bee
aa1490a
 
 
 
 
 
affe37f
 
a83fcff
 
 
 
 
 
e13472e
7f72224
a83fcff
 
7f72224
 
a83fcff
 
e13472e
 
 
 
7f72224
e13472e
 
 
 
 
 
 
 
 
 
a83fcff
c72f0a1
e13472e
7f72224
c72f0a1
 
 
7f72224
c72f0a1
 
 
 
 
 
b2aa446
a83fcff
 
 
 
7f72224
 
 
 
85f794d
a83fcff
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
// ---------------------------------------------------------------------------
// customer-grid / MapView.tsx
// "Map" is a VIEW beside Grid/List/Calendar/Kanban, not a module: it projects
// the SAME pipeline output the grid paints, so the toolbar count, filters and
// sorts mean exactly what they mean on the grid; only the projection changes.
//
// Wave 8 grows it up (I2/I3/I5/I6, contracts C2/C3/C7):
//   I2  wheel/pinch zoom, drag to pan, and a box-select that feeds the grid's
//       OWN selection β€” so the existing "N selected Β· Add to cohort" bar serves
//       the map with no second cohort picker to keep in sync.
//   I3  colour pins by any single-select field (`display.colorField`) + legend.
//   I5  size pins by any numeric/measure field (`display.sizeField`) + legend.
//   I6  a less templatic picture: water wash, land fill, thin C1 strokes,
//       graticule, hover halos.
//
// C7 CALL β€” NO map library, and that call still stands. C7 allowed maplibre-gl
// "with a self-hosted vector/raster-free style"; a tileless maplibre would have
// rendered exactly the geometry below for +230 KB gz on a 251 KB budget.
//
// ⭐⭐ WAVE 37 (R3/R14, W37-T35) β€” THE MAP NOW FETCHES TILES, AND THE OLD NOTE
// HERE SAID THE OPPOSITE. It read: "Nothing is fetched and no coordinate leaves
// the page unless the user deliberately clicks." That was true for two waves and
// is FALSE now, so it is rewritten rather than left to rot. What is true today:
//
//   - a RASTER BASEMAP is fetched, by the browser, straight from the tile
//     provider. Panning the map therefore tells that provider roughly where you
//     are looking. It does NOT tell them who: no record, no name and no address
//     is ever sent, because a tile request carries only a z/x/y grid square that
//     millions of other people also request;
//   - the provider is a SEAM, not a vendor. `/api/v1/geo/providers` serves a URL
//     template plus a credit line, both environment-driven, so pointing this at
//     a paid vendor is configuration and not a rewrite. That seam is the whole
//     reason R14 could defer the Google key without dropping the feature;
//   - the DEFAULT is OpenStreetMap, which needs no key and no billing account.
//     Its credit line is a LICENCE TERM and is rendered, not optional;
//   - GEOCODING is still not automatic and never will be from here (R3). It has
//     its own door, it takes an explicit list of addresses, and it is rate
//     limited in code. Nothing on this surface geocodes anything;
//   - if the tiles fail to load, the vendored vector basemap below is still
//     here and takes over. A map that has lost its network draws the coastline
//     it always drew rather than an empty rectangle.
//
// Honesty rules (rule 8b), carried and extended:
//   - rows WITHOUT coordinates are never silently hidden: the count line reads
//     "N of M mapped", so the unmapped share is the gap between the two numbers;
//   - a pin per row at its geocoded position, no clustering and no jitter (two
//     customers at one address overlap rather than being drawn where they are
//     not);
//   - the colour legend STATES it when a field has more choices than the
//     palette has entries, rather than recycling a colour onto a second meaning;
//   - a row with no value under the size field gets the smallest dot and the
//     legend says so β€” it is never dropped from the map.
// ---------------------------------------------------------------------------

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LogoLoader } from "../ui/LogoLoader";
import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { CatalogSpec, Conjunction, Field, FilterNode, Row, ViewConfig } from "./types";
import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, signal } from "../apiContract";
import { formatDisplay } from "./cells";
import { readDataPath } from "./dataPath";
import { AppFrame } from "./AppFrame";
// C1: Routing and Catalog are Odoo Apps; verify_icons.py holds these two marks to TEMPLATES.
import { AppFrameMarks } from "../apps/templateMarks";
import { CatalogApp } from "../apps/catalog/CatalogApp";
import { RouteApplicationMapView } from "../apps/routing/RouteApplicationMapView";
import type { CatalogApplicationDefinition, CatalogViewSpec } from "./CatalogView";
import { applicationTemplateSurface } from "./viewModes";
import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
import { routingPreferenceKey, bubbleSizeRange, pointRadius, routeFilterSignatureOf } from "./routePrefs";
import type { RoutingCustomerDetail } from "./RouteNav";
import { RouteCustomerPane } from "./RouteNav";
import {
  BASEMAP_DETAIL_K,
  bubbleRadius,
  magnitudeDomain,
  cardBox,
  clientToUser,
  dashPattern,
  fitView,
  formatDuration,
  fromScreen,
  googleMapsUrl,
  googleRouteUrls,
  googleZoomForK,
  graticuleOpacity,
  hairline,
  haversineKm,
  isPlottable,
  normRect,
  parseLatLon,
  pathBounds,
  planRoute,
  pointInPolygon,
  project,
  rotateAt,
  routeFingerprint,
  routeRanks,
  ROUTE_STOP_CAP,
  toScreen,
  unproject,
  WORLD,
  zoomAt,
  zoomLimits,
} from "./mapProjection";
import type { GeoStop, Pt, RouteStamp, View } from "./mapProjection";
import { LP_INK, LP_MAP_SELECTED, LP_PURPLE, LP_PURPLE_DEEP, LP_RED, LP_RED_DEEP, LP_ZONE_FILL_OPACITY, LP_ZONE_STROKE_WIDTH } from "./theme";
import { GoogleMapsMark, RouteNav } from "./RouteNav";
import { endpointRoutePlan, normalizedRouteMapLinks } from "./routeLinks";
import {
  fetchRouteDeliveryRecipients,
  requestRouteDelivery,
  routeInventoryPath,
  routeApplicationPath,
  usesNormalizedCustomerZones,
  zoneCollectionPath,
  zoneItemPath,
  zoneMutationPayload,
} from "./routeZoneApi";
import { mapNavigatorMode, routeSourceStopIds, toggleRouteSelection } from "./routeZoneTypes";
// W51-T28 / R6 + C8 β€” the wave-51 base kit. Every destructive act on this surface goes through
// the ONE dialog, and every panel registers its Escape claim with the ONE arbiter. Neither is
// re-implemented here: `ConfirmDialog` brings its own portal, focus trap, backdrop and focus
// restore, and `useEscapeClose` brings the topmost-wins stack.
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { useEscapeClose } from "../ui/useEscapeClose";
import type {
  MapRouteDto, MapRouteFolderDto, MapRouteSource, MapRouteUpdate, MapZoneDto,
  RouteDeliveryRecipientDirectory, RouteDeliveryDto, RouteDeliveryRequest,
  RouteSelectionRequest, RouteSelectionResponse,
  ZoneGeometry,
} from "./routeZoneTypes";
import "./map.css";
import "../styles/wave46/map-panels.css";
import "../styles/sdlc74/routing.css";

/**
 * W37-T35 β€” THE PROVIDER SEAM, client side.
 *
 * A URL template and a credit line, nothing else. The renderer never learns which company is
 * behind them, which is exactly what makes swapping in a paid provider a config change (R14).
 * These constants are the OFFLINE DEFAULT: `/api/v1/geo/providers` overrides them at mount, and
 * the map still draws if that call never answers.
 */
interface TileProvider {
  url: string;
  attribution: string;
  attributionUrl: string;
  maxZoom: number;
}

const TILES_DEFAULT: TileProvider = {
  url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
  attribution: "Β© OpenStreetMap contributors",
  attributionUrl: "https://www.openstreetmap.org/copyright",
  maxZoom: 19,
};

/** How many tiles one frame may paint. A pathological zoom/pan otherwise asks for thousands, and
 *  a shared free tile service is exactly the wrong place to find that out. */
const TILE_BUDGET = 240;

/** ⭐ OWNER ITEM 1 (2026-08-23) β€” degrees per click of Rotate left / Rotate right, the owner's
 *  own number: *"every click is say rotating the map by 5 degrees"*. 72 clicks is a full turn,
 *  which is why Fit to data doubles as the way back to north. */
const ROTATE_STEP = 5;

/**
 * CSS pixels per SVG user unit, at the width this view is normally painted.
 *
 * β›” MIRRORED FROM `mapProjection.googleZoomForK`, WHICH HARDCODES THE SAME 1.08 AND DOES NOT
 * EXPORT IT. Two copies of one number is [[one-question-two-normalizers]], so `verify_map.py`
 * asserts the constant still reads 1.08 over there. If that gate goes red, these two have drifted
 * and the tile grid will be one zoom level off the hand-off link it is supposed to agree with.
 */
const CSS_PX_PER_UNIT = 1.08;

/** The inverse of `googleZoomForK`: the camera `k` at which one 256px tile paints at ~256 CSS px.
 *  Used for the zoom ceiling, so "as far in as the provider actually serves" is a number and not
 *  a guess. */
function kForTileZoom(z: number): number {
  return (256 * Math.pow(2, z)) / (WORLD * CSS_PX_PER_UNIT);
}

/** Consecutive tile errors before the vendored vector basemap takes back over. Three rather than
 *  one: a single 404 at the edge of coverage is normal and is not an outage. */
const TILE_FAIL_LIMIT = 3;

const VIEW_W = 1000;
const VIEW_H = 620;
const R_MIN = 3.2;
const R_MAX = 15;
const R_PLAIN = 4.5;
const R_NULL = 2.6;
/** A synthetic route-only id. Odoo record ids are positive, so zero cannot become a customer. */
const DEPOT_PID = 0;

/**
 * ⭐⭐ OWNER ITEM 9 β€” ONE SEARCHABLE RECORD PICKER, used twice.
 *
 * The owner asked for search in two places at once: the Start dropdown, and a way to add a record
 * by looking it up in the database. Those are the same control over two different pools, so this
 * is one component rather than two that drift.
 *
 * β›” IT IS A FILTERED LIST, NOT A FLOATING COMBOBOX, and that is deliberate. The route panel is
 * already an absolutely positioned `<aside>` with its own scroll container; a popup listbox inside
 * it needs portal + placement + reposition-on-scroll machinery to sit right, and every one of
 * those is a way for the list to land off-screen. Expanding IN PLACE cannot be mispositioned.
 *
 * ⚠ THE CAP IS STATED, NEVER SILENT (standing rule 1's second sentence). A book of 3,600 customers
 * cannot paint 3,600 rows into a 360px panel, so the list shows the first `LIST_CAP` matches and
 * SAYS how many more the search found; it does not quietly show a tenth of the answer.
 */
const PICKER_LIST_CAP = 40;

function RecordPicker({
  label,
  placeholder,
  emptyNote,
  options,
  currentPid,
  onPick,
}: {
  label: string;
  placeholder: string;
  emptyNote: string;
  options: { pid: number; title: string }[];
  /** Named on the trigger when this picker chooses one of the stops (the Start). */
  currentPid?: number | null;
  onPick: (pid: number) => void;
}) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const needle = q.trim().toLowerCase();
  const matches = useMemo(() => {
    if (!needle) return options;
    return options.filter((o) => o.title.toLowerCase().includes(needle));
  }, [options, needle]);
  const shown = matches.slice(0, PICKER_LIST_CAP);
  const current = currentPid == null ? null : options.find((o) => o.pid === currentPid) || null;

  return (
    <div className="cg-route-picker">
      <span className="cg-route-picker-label">{label}</span>
      <button
        type="button"
        className="cg-route-picker-trigger"
        aria-expanded={open}
        onClick={() => {
          setOpen((v) => !v);
          setQ("");
        }}
        title={open ? `Close the ${label.toLowerCase()} search` : `Search records by name`}
      >
        <span className="cg-route-picker-current">
          {current ? current.title : placeholder}
        </span>
        <svg viewBox="0 0 16 16" aria-hidden="true" className="cg-route-picker-caret">
          <path d="M4 6.5 8 10.5l4-4" />
        </svg>
      </button>
      {open && (
        <div className="cg-route-picker-panel">
          <input
            className="cg-input cg-route-picker-search"
            type="search"
            autoFocus
            value={q}
            placeholder="Search records"
            aria-label={`Search records for ${label.toLowerCase()}`}
            onChange={(e) => setQ(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Escape") {
                e.stopPropagation();
                setOpen(false);
              }
            }}
          />
          {shown.length === 0 ? (
            <span className="cg-route-picker-empty">{needle ? "No record matches that." : emptyNote}</span>
          ) : (
            <div className="cg-route-picker-list" role="listbox">
              {shown.map((o) => (
                <button
                  key={o.pid}
                  type="button"
                  role="option"
                  aria-selected={o.pid === currentPid}
                  className={
                    "cg-route-picker-opt" + (o.pid === currentPid ? " is-on" : "")
                  }
                  onClick={() => {
                    onPick(o.pid);
                    setOpen(false);
                    setQ("");
                  }}
                >
                  {o.title}
                </button>
              ))}
            </div>
          )}
          {matches.length > shown.length && (
            <span className="cg-route-picker-empty">
              Showing the first {shown.length.toLocaleString()} of{" "}
              {matches.length.toLocaleString()} matches. Keep typing to narrow them.
            </span>
          )}
        </div>
      )}
    </div>
  );
}

/** ⭐ OWNER ITEM 7 β€” the travel modes `routes_geo.py` answers. */
type TravelMode = "driving" | "walking";
type RouteModeOffer = { key: TravelMode; label: string; available: boolean };
/** Matches `routes_geo._ROUTE_MODES`, so the toggle is right before the provider call lands. */
const TRAVEL_MODES_DEFAULT: RouteModeOffer[] = [
  { key: "driving", label: "Driving", available: true },
  { key: "walking", label: "Walking", available: true },
];
/** ⚠ ONE frozen empty set, not `new Set()` in a `useState` initialiser argument: the bare call
 *  builds a NEW set on every render, and React only ignores it because the initialiser is read
 *  once. Hoisting it says so, and keeps the identity stable for the memos that depend on it. */
const EMPTY_PIDS: ReadonlySet<number> = new Set<number>();

interface RouteDepot {
  address: string;
  lat: number;
  lon: number;
}

/**
 * The Map starts in the Group-purple family. Colour-by retains its distinct
 * series after that first default, while an unencoded point never regresses to blue.
 * 20%-darkened variants, exactly as the contract specifies for series colour.
 * `fill` is the pastel; `line` is a darker companion, because a C1 pastel
 * measures 1.4-1.9:1 on white and a fill alone would be a smudge (the same
 * measurement that drove the I7c amendment).
 */
const SERIES: { fill: string; line: string }[] = [
  { fill: LP_PURPLE, line: LP_PURPLE_DEEP },
  { fill: "#A5D8B4", line: "#5E9C74" },
  { fill: "#F5D989", line: "#B39A46" },
  { fill: "#F0A8A0", line: "#B76D65" },
  { fill: "#7E99C2", line: "#4A6790" },
  { fill: "#84AD91", line: "#4C7A5C" },
  { fill: "#C4AE6E", line: "#8C7838" },
  { fill: "#C0867F", line: "#8A5049" },
];
/** Anything past the palette, plus the blank bucket. Neutral ON PURPOSE: a
 *  ninth colour that repeats the first would make two meanings look identical. */
const OVERFLOW = { fill: "#D7DBE3", line: "#8A909C" };
const DEFAULT_PIN = { fill: LP_PURPLE, line: LP_PURPLE_DEEP };
const NEGATIVE_PIN = { fill: LP_RED, line: LP_RED_DEEP };
const ZONE_COLOR_CHOICES = [
  { value: LP_PURPLE, label: "Purple" },
  { value: "#A5D8B4", label: "Green" },
  { value: "#F5D989", label: "Yellow" },
  { value: "#F0A8A0", label: "Red" },
  { value: "#C7B7E8", label: "Purple" },
];

/**
 * β›”β›” W47-T02, CAUSE 1 OF THE BLACK BLOB (owner instruction 21, reference image "ERROR 18 Black
 * Blob on the Map.png"): AN SVG SHAPE WITH NO `fill` PAINTS BLACK. Not transparent, not skipped:
 * black is SVG's INITIAL `fill`, so `fill={zone.color}` with an empty colour renders a solid black
 * shape the size of the whole boundary. `saveZone` defaults a colour on ITS OWN write path only
 * (`zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value`), so a Zone that arrived any other
 * way - an older record, an import, a PATCH that omitted the key, a normalized Customer Zone - is
 * colourless at every render site. `MapZoneDto.color` is TYPED `string`, which is precisely why
 * this survived so long: the type is a claim about the API, not a guarantee about the JSON.
 *
 * ⭐ NORMALISED ONCE, HERE, and called by EVERY zone render site rather than sprinkled over the
 * individual `fill`/`stroke` attributes, so a future fourth zone shape cannot miss it the way the
 * keyboard-draft preview was missed before. The fallback is the same value `saveZone` writes, so a
 * repaired Zone does not change colour the moment somebody finally saves it.
 *
 * ⚠ THIS IS A RENDER-PATH FIX ON PURPOSE. A colourless Zone must still DRAW, in a visible
 * fallback; defaulting the colour on the write path or filtering the Zone out of the list would
 * hide the boundary, which is a different defect.
 */
export function zonePaint(color?: string | null): string {
  return typeof color === "string" && color.trim() ? color.trim() : ZONE_COLOR_CHOICES[0].value;
}

/**
 * The STATED screen bound for a Zone radius: the DIAGONAL of the `VIEW_W` x `VIEW_H` canvas,
 * i.e. corner to corner of the 1000x620 viewBox, ~1176.6 user units.
 * ⭐ WHY THE DIAGONAL RATHER THAN `VIEW_W` OR `VIEW_H`: the camera rotates - `tf` puts a `rotate`
 * between the translate and the scale - so width and height swap roles at 90 degrees, and the
 * diagonal is the only single number that still covers the frame at every angle.
 */
const ZONE_RADIUS_SCREEN_MAX = Math.hypot(VIEW_W, VIEW_H);

/**
 * β›”β›” W47-T02, CAUSE 2 OF THE BLACK BLOB. INDEPENDENT OF CAUSE 1, EQUALLY REAL, AND IT SHIPS TOO.
 * `zoneCircles` computed `radius: Math.abs(edge.x - center.x)` from a projected longitude delta
 * and nothing bounded it. A `radiusMeters` that is huge, non-finite or negative - a bad import, a
 * NaN centre latitude driving the `cos` term, a degrees/metres mix-up - projects to a radius of
 * millions of user units and paints a filled disc over the entire canvas: the same "really Huge
 * Blob" symptom arriving from the other direction. Whichever cause a previous attempt found, the
 * other one was still there, which is why the owner has reported this repeatedly.
 *
 * `radius` is in the PRE-TRANSFORM user space of `<g transform={tf}>`, so the on-screen radius is
 * `radius * k`. Dividing the bound by `k` is what makes this a SCREEN bound at every zoom rather
 * than a user-space one that goes slack the moment somebody zooms in.
 *
 * ⚠ THE TRADEOFF, STATED RATHER THAN HIDDEN: clamping an off-centre monster can uncover canvas
 * that the unclamped disc used to cover. Accepted deliberately - a circle whose screen radius
 * exceeds the viewport diagonal is the defect, not a use case, so a distance-aware bound would
 * buy nothing real and would cost an invariant a gate can hold.
 *
 * β›” NON-FINITE AND NEGATIVE ARE FOLDED IN HERE, not only the too-large case: SVG `r` must be a
 * finite number >= 0, and `r="NaN"` or `r="-5"` is the unbounded case wearing a different mask.
 */
export function clampZoneRadius(radius: number, k?: number): number {
  if (!Number.isFinite(radius) || radius <= 0) return 0;
  const zoom = typeof k === "number" && Number.isFinite(k) && k > 0 ? k : 1;
  return Math.min(radius, ZONE_RADIUS_SCREEN_MAX / zoom);
}

/** Move a durable GeoJSON boundary without changing its topology or membership snapshot. */
export function translateZoneGeometry(
  geometry: ZoneGeometry, delta: { lon: number; lat: number }
): ZoneGeometry {
  if (geometry.type === "Circle") return {
    type: "Circle",
    center: [Math.max(-180, Math.min(180, geometry.center[0] + delta.lon)), Math.max(-90, Math.min(90, geometry.center[1] + delta.lat))],
    radiusMeters: geometry.radiusMeters,
  };
  const point = (pair: number[]) => [
    Math.max(-180, Math.min(180, pair[0] + delta.lon)),
    Math.max(-90, Math.min(90, pair[1] + delta.lat)),
  ];
  if (geometry.type === "Polygon") {
    return { type: "Polygon", coordinates: (geometry.coordinates as number[][][])
      .map((ring) => ring.map(point)) };
  }
  return { type: "MultiPolygon", coordinates: (geometry.coordinates as number[][][][])
    .map((polygon) => polygon.map((ring) => ring.map(point))) };
}

/** How many draggable corners one boundary ring may show. A shape a person DREW has a handful;
 *  anything past this was traced by the lasso, one coordinate per pointermove, and its dots
 *  would obscure the Zone rather than let anyone reshape it. See the render site. */
const ZONE_VERTEX_HANDLE_MAX = 24;

/** Where a single vertex lives inside a boundary. `polygonIndex` is meaningless for a plain
 *  Polygon (it is always 0) and load-bearing for a MultiPolygon; both are carried so one
 *  address works for either shape. */
interface ZoneVertexAddress {
  polygonIndex: number;
  ringIndex: number;
  vertexIndex: number;
}

/**
 * ⭐ W46-T28 β€” MOVE ONE VERTEX, leaving every other point where it was. Owner instruction 16:
 * *"the zone vertices should be a dot that is draggable so I can minimize or expand a zone."*
 * `translateZoneGeometry` above is the whole-boundary sibling; this is the reshape.
 *
 * β›” A GeoJSON RING IS CLOSED: its first and last coordinate are THE SAME POINT stored twice.
 * Writing only the index that was grabbed tears the ring open at that seam, and the polygon then
 * renders with a slit that no gate can see. Vertex 0 and the closing vertex always move
 * together, which is the one rule this function exists to hold.
 */
export function moveZoneVertex(
  geometry: ZoneGeometry, at: ZoneVertexAddress, to: { lon: number; lat: number }
): ZoneGeometry {
  if (geometry.type === "Circle") return geometry;
  const moved = [
    Math.max(-180, Math.min(180, to.lon)),
    Math.max(-90, Math.min(90, to.lat)),
  ];
  const editRing = (ring: number[][]) => {
    if (at.vertexIndex < 0 || at.vertexIndex >= ring.length) return ring;
    const next = ring.map((pair) => [...pair]);
    const last = next.length - 1;
    const closed = last > 0 && next[0][0] === next[last][0] && next[0][1] === next[last][1];
    next[at.vertexIndex] = [...moved];
    if (closed && at.vertexIndex === 0) next[last] = [...moved];
    if (closed && at.vertexIndex === last) next[0] = [...moved];
    return next;
  };
  if (geometry.type === "Polygon") {
    return { type: "Polygon", coordinates: (geometry.coordinates as number[][][])
      .map((ring, ringIndex) => (ringIndex === at.ringIndex ? editRing(ring) : ring)) };
  }
  return { type: "MultiPolygon", coordinates: (geometry.coordinates as number[][][][])
    .map((polygon, polygonIndex) => (polygonIndex !== at.polygonIndex ? polygon
      : polygon.map((ring, ringIndex) => (ringIndex === at.ringIndex ? editRing(ring) : ring)))) };
}

/** C3's durable map-domain DTO. Zones are not generic fields: geometry, visibility and the
 * membership snapshot only make sense to this projection. */
type MapZone = MapZoneDto;

interface ZoneMove {
  zone: MapZone;
  geometry: ZoneGeometry;
  start: Pt;
}

/** An in-flight vertex drag. It carries the geometry it started from, so every pointermove
 *  recomputes from the ORIGINAL rather than compounding its own previous answer. */
interface ZoneVertexDrag extends ZoneVertexAddress {
  zone: MapZone;
  geometry: ZoneGeometry;
}

/** Immutable provenance supplied by the host grid for a scheduled route snapshot. */
export interface RouteSourceView {
  id: string;
  name: string;
  /** Exact saved config the API compares before minting immutable route provenance. */
  config: ViewConfig;
}

/* ═══════ R10 (W50-T14) β€” THE MAP REMEMBERS WHERE YOU WERE, PER PERSON ═══════
 *
 * Owner ruling R10: map state (viewport, open route, panel) is remembered per person, per view,
 * in this browser, and it NEVER writes the saved view.
 *
 * β›” THE SECOND HALF IS A PROHIBITION, NOT a nice-to-have. This is a READER's preference and it
 * goes to `localStorage` and nowhere else: no `persistView`, no view upsert, no mutation of
 * `activeView.config` and no `onManagedRouteViewState` call on this path. A colleague opening the
 * same saved view must see the view as it was SAVED, not wherever the last person left the camera.
 *
 * ⚠ `localStorage` CAN THROW OUTRIGHT (private mode, blocked site data), so every read and every
 * write is wrapped and the map draws correctly with no stored value at all. Same discipline as
 * `zoneFillOpacity` below, and for the same reason.
 *
 * ⚠ A STORED VIEWPORT IS VALIDATED, NOT TRUSTED. It is restored BEFORE the first auto-fit and
 * suppresses it, so a corrupt `k` of zero or a NaN translate would leave a permanently blank map.
 * Every number is range-checked on the way in instead.
 */
const MAP_MEMORY_PREFIX = "cg-map:";

/** How long the map settles before a pan or a zoom is written. A wheel gesture is dozens of
 *  renders; one write per render would be a storage call per animation frame. */
const MAP_MEMORY_DEBOUNCE_MS = 400;

/** What one reader's browser remembers for one saved view. Every field is optional: a memory
 *  written by an older build must never stop the map drawing. */
interface MapMemory {
  view?: { k: number; tx: number; ty: number; rot?: number };
  routeId?: string | null;
  navigator?: "routes" | "zones" | null;
}

/** Apps remember their own panel and camera; standalone maps retain the saved View key. */
function mapMemoryKey(tableKey: string, viewId: string | null | undefined, applicationId?: string): string | null {
  if (applicationId) return routingPreferenceKey(`${MAP_MEMORY_PREFIX}${tableKey}`, applicationId);
  if (!tableKey || !viewId) return null;
  return `${MAP_MEMORY_PREFIX}${tableKey}:${viewId}`;
}

function readMapMemory(key: string | null): MapMemory | null {
  if (!key) return null;
  try {
    const raw = window.localStorage.getItem(key);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as MapMemory | null;
    if (!parsed || typeof parsed !== "object") return null;
    const stored = parsed.view;
    const view = stored
      && Number.isFinite(stored.k) && stored.k > 0
      && Number.isFinite(stored.tx) && Number.isFinite(stored.ty)
      && (stored.rot === undefined || Number.isFinite(stored.rot))
      ? { k: stored.k, tx: stored.tx, ty: stored.ty, rot: stored.rot }
      : undefined;
    const mode = parsed.navigator === "routes" || parsed.navigator === "zones" ? parsed.navigator : null;
    const routeId = typeof parsed.routeId === "string" && parsed.routeId ? parsed.routeId : null;
    return { view, routeId, navigator: mode };
  } catch {
    return null;
  }
}

function writeMapMemory(key: string | null, memory: MapMemory): void {
  if (!key) return;
  try {
    window.localStorage.setItem(key, JSON.stringify(memory));
  } catch {
    /* a reader who cannot store a preference still gets a working map for this session */
  }
}

interface MapPoint {
  pid: number;
  title: string;
  p: Pt;
  /** The ORIGINAL coordinate, kept beside the projected one so the Google
   *  hand-off links to the exact geocode we plotted rather than to a round-trip
   *  through the projection. */
  lat: number;
  lon: number;
  colorKey: string | null;
  size: number | null;
  /** The RAW cell values behind the two encodings. The hover card formats these
   *  with `formatDisplay`, the grid's own formatter β€” `colorKey` is trimmed for
   *  bucketing and `size` is coerced for the bubble scale, so neither is what a
   *  human should be shown. */
  colorVal: Row[keyof Row];
  sizeVal: Row[keyof Row];
}

function coord(v: Row[keyof Row]): number | null {
  if (v == null || v === "") return null;
  const n = typeof v === "number" ? v : Number(v);
  return Number.isFinite(n) ? n : null;
}

type CoordinateFields = { latitude: Field; longitude: Field };

/** Resolve one row through database setup, then legacy composite setup, then built-in transport. */
function rowCoordinates(
  row: Row,
  coordinateFields?: CoordinateFields,
  coordField?: Field,
  sessionCoordinates?: ReadonlyMap<number, { lat: number; lon: number }>,
): { lat: number; lon: number } | null {
  const sessionPoint = sessionCoordinates?.get(row.pid) ?? null;
  if (coordinateFields) {
    const lat = coord(row[coordinateFields.latitude.key]);
    const lon = coord(row[coordinateFields.longitude.key]);
    return lat == null || lon == null || !isPlottable(lat, lon) ? sessionPoint : { lat, lon };
  }
  if (coordField?.key) return parseLatLon(row[coordField.key]) ?? sessionPoint;
  const lat = coord(row.lat);
  const lon = coord(row.lon);
  return lat == null || lon == null || !isPlottable(lat, lon) ? sessionPoint : { lat, lon };
}

function numOrNull(v: Row[keyof Row]): number | null {
  if (v == null || v === "") return null;
  const n = typeof v === "number" ? v : Number(v);
  return Number.isFinite(n) ? n : null;
}

/** W46-T17 β€” the draw glyph for the Zone arming button. A pen over a dotted
 *  outline: what the button does, in the same 16x16 box and the same
 *  `currentColor`/`fill="none"` idiom as the camera controls below.
 *  ⚠ It lives here rather than in `iconShapes.ts` only because that shared
 *  vocabulary belongs to another lane this wave. Its home there is owed. */
function DrawZoneIcon() {
  return (
    <svg className="cg-zone-draw-ico" viewBox="0 0 16 16" aria-hidden="true"
      fill="none" stroke="currentColor" strokeWidth="1.4"
      strokeLinecap="round" strokeLinejoin="round">
      <path d="M2.4 9.6V3.2h5.2" strokeDasharray="2 1.6" />
      <path d="M2.4 12.8h4.2" strokeDasharray="2 1.6" />
      <path d="M13.6 3.1 8.2 8.5l-.7 2.5 2.5-.7 5.4-5.4z" />
    </svg>
  );
}

export function MapViewSurface(props: Parameters<typeof MapViewSurfaceContent>[0]) {
  return <MapViewSurfaceContent key={JSON.stringify([props.tableKey, props.applicationId ?? ""])} {...props} />;
}

function MapViewSurfaceContent({
  rows,
  field,
  coordinateFields,
  coordField,
  colorField,
  sizeField,
  selectedPids,
  onSelectPids,
  onOpen,
  onGeocoded,
  onRouteFieldCreated,
  routePanelOpen: requestedRoutePanelOpen,
  allRows,
  activeView,
  tableKey,
  onManagedRouteViewState,
  filterRestore = null,
  onZoneChanged,
  applicationName,
  applicationId,
  routingFilters,
  customerDetail = null,
  onCustomerBack,
  routeApplication = false,
  geocodeSessionOnly = false,
  hosted = false,
  recordsPending = false,
  pinClickSelects = false,
}: {
  /** DISTINCT data rows from the full pipeline, overlay edits layered β€” the
   *  calendar/kanban contract, verbatim. */
  rows: Row[];
  /** The locked identity column β€” pin tooltips and aria labels. */
  field: Field;
  /** The database's configured latitude and longitude fields, resolved by the caller.
   *
   * β›” OPTIONAL, AND THE ABSENT CASE IS NOT "NO MAP" β€” it is the `lat`/`lon` column pair the
   * customers mirror has always carried. */
  coordinateFields?: CoordinateFields;
  /**
   * Legacy composite location field from an older saved View or prerelease database setup.
   * It remains a backwards-compatible fallback after the database-owned coordinate pair.
   *
   * That fallback is the ONLY reason this change is not a migration: every map without a custom
   * source keeps painting exactly what it painted before.
   */
  coordField?: Field;
  /** I3 β€” the view's `display.colorField`, already resolved to a real field. */
  colorField?: Field;
  /** I5 β€” the view's `display.sizeField`, already resolved to a real field. */
  sizeField?: Field;
  /** The grid's selection, shared: pins render selected, and the existing
   *  selection bar is what offers "Add to cohort" (C3). */
  selectedPids: ReadonlySet<number>;
  onSelectPids: (pids: number[], mode: "replace" | "add") => void;
  onOpen: (pid: number) => void;
  /**
   * W37-T37 (R4 / C7) β€” where looked-up coordinates go. The map does the ASKING; the host does the
   * WRITING, through whichever cell door it already owns.
   *
   * β›” THE MAP DELIBERATELY HAS NO WRITER OF ITS OWN. A second path that can put values into cells
   * would sit outside every guard the grid's own edit door carries, and this view is the last place
   * that should own one. Absent callback = the control does not render unless a Route Application
   * explicitly keeps its results in this map session, so every lookup still has somewhere to land.
   */
  onGeocoded?: (writes: { pid: number; value: string }[]) => void;
  onRouteFieldCreated?: (key: string) => void;
  routePanelOpen: boolean;
  /** The real active View driving this map, never a map-local synthetic id. */
  activeView: RouteSourceView | null;
  /** Canonical database identity for durable, table-scoped Zones. */
  tableKey: string;
  /** C2 handoff: the server alone returns the managed route-membership clause. */
  onManagedRouteViewState?: (viewState: Record<string, unknown>, applicationId?: string) => void;
  /** S72-T60: the host restored saved filters. A change to exactly this signature is a restore,
   *  so it keeps the route selection and posts nothing. Each `seq` is honoured once. */
  filterRestore?: { seq: number; signature: string } | null;
  /** Customer Zones also project into the read-only grid field, so a successful normalized
   * mutation invalidates the host row payload instead of leaving that projection stale. */
  onZoneChanged?: (applicationId?: string) => void;
  /** The saved Routing App name and the identity that scopes its assets and preferences. */
  applicationName?: string;
  applicationId?: string;
  /** The host supplies its existing filter controls above the saved Routes. */
  routingFilters?: ReactNode;
  customerDetail?: RoutingCustomerDetail | null;
  onCustomerBack?: () => void;
  /** Opens the Routes navigator as presentation state for a Routing Application. The host's
   * ordinary route toggle remains authoritative everywhere else. */
  routeApplication?: boolean;
  /** Route templates may map an address without owning a coordinate cell. Successful lookups
   * stay in this mounted map so the Application can plot them without inventing a database field. */
  geocodeSessionOnly?: boolean;
  /**
   * ⭐⭐ OWNER ITEM 9 β€” THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
   *
   * β›” "UNFILTERED" MEANS UNFILTERED BY THE VIEW, NOT UNWALLED, and the distinction is the whole
   * safety of this prop. The host passes `scopedRows`, which is the row set AFTER `allowed_pids`
   * and the business-unit scope and BEFORE the view's own filters and search. So a person
   * planning a day can reach a customer their current filter hides, and cannot reach one their
   * book does not contain. Absent = the picker does not render, rather than rendering empty.
   */
  allRows?: Row[];
  /** S72-T63 / C3: a grid mounted at an address. The map then never reads `location.hash`. */
  hosted?: boolean;
  recordsPending?: boolean;
  /** Table opts in. Direct surface consumers retain their existing pin gestures. */
  pinClickSelects?: boolean;
}) {
  const routingAlive = useRef(true);
  useEffect(() => {
    routingAlive.current = true;
    return () => { routingAlive.current = false; };
  }, []);
  const routingFetch = useCallback((path: string, init?: RequestInit) => {
    if (!routingAlive.current) return Promise.reject(new DOMException("Routing App closed", "AbortError"));
    return fetch(routeApplicationPath(path, applicationId), init);
  }, [applicationId]);
  const [hoverPid, setHoverPid] = useState<number | null>(null);
  // R23 makes the Routing app's rail constant. Previously the host prop and local seed could
  // disagree: Escape could close the seed and a host mode change could clear the prop. Neither
  // path can close the app's rail now; the Data routing view still follows the host prop.
  const routePanelOpen = routeApplication || requestedRoutePanelOpen;
  /* R10 β€” READ ON MOUNT, BEFORE THE FIRST FIT, and that is why this is a lazy initializer rather
     than an effect. The auto-fit below seeds `view` from the first `fit` it can compute; a restore
     that ran afterwards would be overwritten by it, and one that ran just before would still have
     painted the fitted camera for a frame. Seeding the state IS the ordering. */
  const [restoredMap] = useState<MapMemory | null>(() => readMapMemory(mapMemoryKey(tableKey, activeView?.id, applicationId)));
  /* ⚠ DECLARED HERE, AT THE TOP, AND NOT BESIDE THE `view` STATE THAT CONSUMES IT. The Route and
     navigator restore effects far below take `restoredMap` as a dependency, and a dependency array
     is evaluated DURING render β€” a `const` declared later in this body is in its temporal dead zone
     at that point and throws, even though the effect callback itself would have run fine. */
  // I18-R β€” the route planner. Off until asked for: a route drawn over a
  // selection nobody asked to route is just clutter.
  const [routeOn, setRouteOn] = useState(false);
  /** Route navigation is an index first; planning begins only after the explicit Create route
   * action or an existing saved route has been opened. */
  /** ⭐⭐ OWNER 2026-08-31 - *"wtf I don't see the button to make it either 1 single trip or
   *  round trip. The algorithm was there its not being displayed anymore"*. Correct, and the
   *  record was in the code: this state's ONLY writer, `setRoundTrip`, sat in the retired
   *  `void []` compatibility list below, so the value was pinned at false with no control
   *  anywhere while `planRoute`, `twoOptOrder`, `tourLength` and `routes_geo.py` all still read
   *  it. It lives HERE, not in `RouteNav`, because the drawn `plan` and the panel's drive time
   *  have to answer the same question - two copies is how they come to disagree. */
  const [roundTrip, setRoundTrip] = useState(false);
  const [routeStartPid, setRouteStartPid] = useState<number | null>(null);
  const [routeEndPid, setRouteEndPid] = useState<number | null>(null);
  const askRoadRef = useRef(false);
  /**
   * W37-T36 β€” A HAND-PICKED STOP ORDER, pids in visiting sequence, or null for the planner's.
   *
   * The planner solves for distance; a person routing a day of visits is solving for an
   * appointment at eleven. So the arithmetic proposes and the human disposes, and the foot row's
   * `Update calculation` hands it back (wave 41 / R13: setting this to null IS the re-solve, and
   * it now travels with the road refetch rather than beside it).
   * Kept as pids rather than indices because the selection can change underneath it.
   */
  const [routeOrder, setRouteOrder] = useState<number[] | null>(null);
  /**
   * β›” OWNER ITEM 6 β€” THE DEPOT UI IS GONE AND THIS STATE DELIBERATELY IS NOT. The owner removed
   * the "Optional route start" section: the start is the record dropdown and nothing else. What
   * stays is the PLUMBING it fed (`depotPoint` -> `routable` -> `plan.depot`, and the pin), so
   * this is a hotfix that removes a control rather than a refactor that removes a concept, and a
   * column somebody already saved with a depot still round-trips through the server untouched
   * (nothing in this file SENDS the key, so `route_order_write` preserves what it stored).
   * It is therefore always null now, and `Clear` is what keeps that honest.
   */
  const [depot, setDepot] = useState<RouteDepot | null>(null);
  /**
   * ⭐ OWNER ITEM 7 β€” DRIVING OR WALKING, and the modes come from the SERVER rather than being
   * hardcoded here: a mode this deployment has no router for must not be offered
   * ([[permitted-is-not-answerable]]). The default list matches `routes_geo.py`'s own, so the
   * toggle works before the provider call lands and keeps working if it never does.
   */
  const [travelMode, setTravelMode] = useState<TravelMode>("driving");
  const [travelModes, setTravelModes] = useState<RouteModeOffer[]>(TRAVEL_MODES_DEFAULT);
  /**
   * ⭐⭐ OWNER ITEM 9 β€” records added to the route BY HAND, from outside the view's filter.
   *
   * β›” THEY JOIN THE MAP'S OWN ROW SET RATHER THAN A PARALLEL STOP LIST, which is what keeps the
   * counts one story: an added record gets a pin, gets counted in "N of M mapped", and lands in
   * the "no location, so not routed" chip if it has no coordinate. A second list beside `points`
   * would have had to re-derive every one of those and would have drifted from the first.
   */
  const [addedPids, setAddedPids] = useState<ReadonlySet<number>>(EMPTY_PIDS);
  /** C3 Zone chooser/editor state. `null` means the tenant read has not answered; an empty
   * array is an honest, editable no-Zones state. */
  const [zones, setZones] = useState<MapZone[] | null>(null);
  /** C2 named-route read model. */
  const [namedRoutes, setNamedRoutes] = useState<MapRouteDto[]>([]);
  // `[]` cannot tell "not read yet" from "none": RouteNav says Loading until the first read answers.
  const [routesLoaded, setRoutesLoaded] = useState(false);
  // A failed read is not "no routes": RouteNav shows a load error and keeps the last good list.
  const [routesLoadError, setRoutesLoadError] = useState(false);
  const [routeFolders, setRouteFolders] = useState<MapRouteFolderDto[]>([]);
  const [routeDeliveryRecipients, setRouteDeliveryRecipients] = useState<RouteDeliveryRecipientDirectory | null>(null);
  const [deliveryRecipientError, setDeliveryRecipientError] = useState<string | null>(null);
  const [createdRoute, setCreatedRoute] = useState<MapRouteDto | null>(null);
  const [selectedRouteIds, setSelectedRouteIds] = useState<ReadonlySet<string>>(new Set());
  /** The Route detail is the only pin-edit target. Route selection never chooses it implicitly. */
  const [activeRouteId, setActiveRouteId] = useState<string | null>(null);
  const pendingInboxRoute = useRef<string | null>(null);
  useEffect(() => {
    const openRoute = (event: Event) => {
      const routeId = String((event as CustomEvent<{ routeId?: string }>).detail?.routeId ?? "");
      if (!routeId) return;
      pendingInboxRoute.current = routeId;
      setActiveRouteId(routeId);
    };
    window.addEventListener("aios:route-open", openRoute);
    return () => window.removeEventListener("aios:route-open", openRoute);
  }, []);
  useEffect(() => {
    // C3: a hosted map has no page address, so a Route opens only through `aios:route-open`.
    if (hosted) return;
    const openHashRoute = () => {
      const queryAt = window.location.hash.indexOf("?");
      if (queryAt < 0) return;
      const routeId = new URLSearchParams(window.location.hash.slice(queryAt + 1)).get("route");
      if (!routeId) return;
      pendingInboxRoute.current = routeId;
      setActiveRouteId(routeId);
    };
    openHashRoute();
    window.addEventListener("hashchange", openHashRoute);
    return () => window.removeEventListener("hashchange", openHashRoute);
  }, [hosted]);
  const [routePinPrompt, setRoutePinPrompt] = useState<{
    routeId: string; customerPid: number; title: string; present: boolean;
  } | null>(null);
  const [routePinNotice, setRoutePinNotice] = useState<string | null>(null);
  const [routePinBusy, setRoutePinBusy] = useState(false);
  /* ⭐ W51-T28 / R6 β€” THE TWO PENDING CONFIRMS, HOISTED TO THE COMPONENT so the dialog outlives
     the control that opened it. Both replaced a `window.confirm`, which blocked the JS thread and
     therefore needed no state at all; a real dialog paints on a later frame, so the subject of the
     question has to be held somewhere that survives that frame. */
  const [pendingRouteInclude, setPendingRouteInclude] = useState<MapRouteDto | null>(null);
  const [pendingZoneDelete, setPendingZoneDelete] = useState<MapZone | null>(null);
  const [managedRouteViewState, setManagedRouteViewState] = useState<Record<string, unknown> | null>(null);
  const [routeSelectionWarning, setRouteSelectionWarning] = useState<string | null>(null);
  const [activeZoneIds, setActiveZoneIds] = useState<ReadonlySet<string>>(new Set());
  const [zoneNavigatorOpen, setZoneNavigatorOpen] = useState(false);
  const [zoneEditorOpen, setZoneEditorOpen] = useState(false);
  const [zoneEditorId, setZoneEditorId] = useState("");
  const [zoneName, setZoneName] = useState("");
  const [zoneColor, setZoneColor] = useState(ZONE_COLOR_CHOICES[0].value);
  /* ⭐⭐ OWNER, 2026-08-31: *"let's make the Zone opacity toggleable under the Zone configuration
     module"*, in the same breath as correcting the fill to 80%. This state is the SINGLE WRITER of
     both seams contract C1 names -- it drives the `--lp-zone-fill` custom property inline on
     `.cg-mapview` AND the keyboard draft's `fillOpacity` attribute -- so the two can no longer
     drift by hand, which is what C1 was asking a person to prevent.
     ⚠ A DISPLAY PREFERENCE, NOT ZONE DATA, and that is a deliberate scope call on a hotfix. It is
     stored per reader in `localStorage` rather than on the Zone record: persisting it server-side
     would mean a `MapZoneDto` field, a route and a store write, which is a schema change and not a
     hotfix. If the owner wants opacity to travel WITH a Zone to other viewers, that is the
     follow-up this comment exists to name.
     ⚠ `localStorage` can throw outright (private mode, blocked site data), so every read and
     write is guarded and falls back to the token rather than leaving the map unpainted. */
  const [zoneFillOpacity, setZoneFillOpacity] = useState<number>(() => {
    try {
      const raw = window.localStorage.getItem("cg-zone-fill-opacity");
      const parsed = raw === null ? NaN : Number(raw);
      return Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 ? parsed : LP_ZONE_FILL_OPACITY;
    } catch {
      return LP_ZONE_FILL_OPACITY;
    }
  });
  useEffect(() => {
    try {
      window.localStorage.setItem("cg-zone-fill-opacity", String(zoneFillOpacity));
    } catch {
      /* a reader who cannot store a preference still gets to SET one for this session */
    }
  }, [zoneFillOpacity]);
  const [zoneDrawShape, setZoneDrawShape] = useState<"polygon" | "circle">("polygon");
  const [drawnZoneGeometry, setDrawnZoneGeometry] = useState<ZoneGeometry | null>(null);
  const [zoneKeyboardDraft, setZoneKeyboardDraft] = useState<{
    shape: "polygon" | "circle";
    cursor: Pt;
    points: Pt[];
    center?: Pt;
  } | null>(null);
  const mapFrameRef = useRef<HTMLDivElement | null>(null);
  const [zoneMove, setZoneMove] = useState<ZoneMove | null>(null);
  const [zoneVertex, setZoneVertex] = useState<ZoneVertexDrag | null>(null);
  const [zoneGeometryDraft, setZoneGeometryDraft] = useState<{ id: string; geometry: ZoneGeometry } | null>(null);
  const [zoneBusy, setZoneBusy] = useState(false);
  const [zoneErr, setZoneErr] = useState<string | null>(null);
  const zoneRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
    generation: 0,
    controller: null,
  });
  const routeRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
    generation: 0,
    controller: null,
  });
  const deliveryRecipientRequestRef = useRef<{ generation: number; controller: AbortController | null }>({
    generation: 0,
    controller: null,
  });
  const normalizedCustomerZones = usesNormalizedCustomerZones(tableKey);
  const mapNavigator = mapNavigatorMode(routePanelOpen, zoneNavigatorOpen);
  const activeNamedRoute = useMemo(
    () => activeRouteId ? namedRoutes.find((route) => route.id === activeRouteId) || null : null,
    [activeRouteId, namedRoutes]
  );
  useEffect(() => {
    const routeId = pendingInboxRoute.current;
    if (!routeId || !namedRoutes.some((route) => route.id === routeId)) return;
    pendingInboxRoute.current = null;
    setActiveRouteId(routeId);
  }, [namedRoutes]);
  useEffect(() => {
    setRoutePinPrompt(null);
    setRoutePinNotice(null);
  }, [activeRouteId]);
  useEffect(() => {
    if (activeRouteId && !activeNamedRoute) setActiveRouteId(null);
  }, [activeNamedRoute, activeRouteId]);
  useEffect(() => {
    if (routePanelOpen) {
      return;
    }
    setZoneNavigatorOpen(false);
    setZoneEditorOpen(false);
    setActiveRouteId(null);
    setRoutePinPrompt(null);
    setRoutePinNotice(null);
    setRoutePinBusy(false);
  }, [routePanelOpen]);
  /* ══════════ R10 β€” THE RESTORE HALF, AND IT SITS *AFTER* THE CLOSE EFFECT ON PURPOSE ══════════
     Both react to `routePanelOpen`, and the effect above clears the Route detail and the Zone
     navigator whenever the panel is shut. Declared before it, these two would restore into a state
     the close effect then wiped in the same commit. Declared after, and gated on the panel being
     OPEN, they can only ever run when the close effect has taken its early return.

     ⚠ `routePanelOpen` is the effective presentation answer: the host's ordinary toggle OR the
     Routing Application's local first-paint seed. Both therefore reach these same restore effects;
     the Application path does not bypass them or write the saved View configuration. */
  const navigatorRestored = useRef(false);
  useEffect(() => {
    if (navigatorRestored.current || !routePanelOpen) return;
    navigatorRestored.current = true;
    if (restoredMap?.navigator === "zones") setZoneNavigatorOpen(true);
  }, [restoredMap, routePanelOpen]);
  /* β›” ONE SHOT, AND BOUNDED. The named-Route read answers asynchronously, so this has to wait for
     `namedRoutes` β€” but it must NOT stay armed after that, or a later refresh of the list would
     re-open a route the reader had since closed. The flag is set as soon as the list has answered,
     whether or not the remembered route survived in it. */
  const routeRestored = useRef(false);
  useEffect(() => {
    if (routeRestored.current || !routePanelOpen) return;
    const routeId = restoredMap?.routeId;
    if (!routeId) {
      routeRestored.current = true;
      return;
    }
    if (namedRoutes.length === 0) return;
    routeRestored.current = true;
    if (namedRoutes.some((route) => route.id === routeId)) setActiveRouteId(routeId);
  }, [namedRoutes, restoredMap, routePanelOpen]);
  /**
   * W37-T36 β€” the ROAD answer, which is the half arithmetic cannot produce.
   *
   * β›” FETCHED ONLY WHEN ASKED (R3), and "asked" means a click, never a render and never a
   * selection change. When the stops or their order move underneath a fetched route, the geometry
   * is marked STALE and stays on screen greyed rather than being silently refetched or silently
   * left looking current. A route that quietly describes a different set of stops than the one on
   * screen is the failure mode worth spending a state field to prevent.
   */
  const [road, setRoad] = useState<
    {
      km: number;
      minutes: number;
      line: number[][];
      key: string;
      attribution: string;
      /** WHICH mode produced these numbers, so the label can never outrun the answer. */
      mode: TravelMode;
    } | null
  >(null);
  const [roadBusy, setRoadBusy] = useState(false);
  const [roadErr, setRoadErr] = useState<string | null>(null);
  /** The legacy on-map planner still chunks a preview at ten stops. Scheduled normalized Routes
   * own their independently editable 2-10 choice inside RouteNav. */
  const mapsPerLink = 10;
  const [routeCopyMsg, setRouteCopyMsg] = useState<string | null>(null);
  const [routeDeliveries, setRouteDeliveries] = useState<RouteDeliveryDto[] | null>(null);
  /** Which saved column a save writes to. `""` = a new field, named in the prompt below. */
  const [saveTarget, setSaveTarget] = useState("");
  /**
   * ⭐⭐ OWNER, 2026-08-23 β€” WHICH SAVED ROUTE IS BEING **SHOWN**, which is not the same
   * question as which column a save WRITES TO.
   *
   * Owner: *"when I click the Route navigation button. I should be able to choose any Route
   * field I want to see the Routes."* Before this the only route control was `saveTarget`: it
   * appeared behind `plan &&` (so you could not reach it until you had already solved something
   * else), it listed `mine` columns only, and picking one changed nothing on the map because it
   * named a WRITE destination. Reading a colleague's plan was not expressible at all.
   *
   * β›” TWO STATES BECAUSE THEY ARE TWO PERMISSIONS. Anyone the column was shared with may OPEN
   * it; only its planner or an admin may re-solve it (`route_order_write`'s creator-or-admin
   * wall, reported as `mine`). Collapsing them into one control would either offer a Save that
   * earns a 403 or hide a route the person is allowed to read.
   */
  const [, setOpenedRoute] = useState("");
  const [openErr, setOpenErr] = useState<string | null>(null);
  /**
   * ⭐⭐ OWNER ITEM 5 (2026-08-23) β€” THE NAME IS ASKED FOR, AND ITS DEFAULT COMES FROM THE SERVER.
   *
   * Owner: *"When we click the newly renamed 'Save route' it should prompt the user to Name the
   * route, with the default as Route 1, or Route 2, etc."*
   *
   * β›” THE SERVER-SIDE ALLOCATOR IS GONE. `nextLabel` used to come from
   * `GET /customers/route-order`, which counted the whole shared stratum of legacy route COLUMNS
   * so a user with no grant on `route_route_1` was never pre-filled a name they would then be
   * refused. That door and that stratum are deleted, and no client reads this value: W47-T09 / R9
   * had already retired the naming panel, which is why the constant below is parked in the
   * `void [...]` list rather than rendered.
   *
   * ⚠ WHOEVER PUTS THE NAMING PANEL BACK: derive the pre-fill from the normalized Routes the
   * panel already holds, NOT from a column listing -- there are no columns to count any more, and
   * the refusal the old allocator existed to prevent (`field_key_taken` on a name this panel put
   * in the box) cannot arise on a Route record, whose name is not a store key.
   */
  const nextLabel = "";
  const [naming, setNaming] = useState(false);
  const [nameDraft, setNameDraft] = useState("");
  const [saveBusy, setSaveBusy] = useState(false);
  const [saveMsg, setSaveMsg] = useState<string | null>(null);
  const [saveErr, setSaveErr] = useState<string | null>(null);
  /**
   * W37-T37 β€” the address lookup's own progress, and it exists so the WAIT IS VISIBLE.
   *
   * β›” R3/R14: a lookup runs only when a person asks, for the records that person chose, and at
   * roughly one address per second. That last part means a real run TAKES MINUTES, so hiding it
   * behind a spinner would be the difference between a wait and a hang. `done` of `total` is on
   * screen the whole time, and it counts records rather than requests because that is the unit the
   * person selected.
   */
  const [geo, setGeo] = useState<{
    busy: boolean; done: number; total: number; found: number; error: string | null;
  }>({ busy: false, done: 0, total: 0, found: 0, error: null });
  const [sessionCoordinates, setSessionCoordinates] = useState<
    ReadonlyMap<number, { lat: number; lon: number }>
  >(() => new Map());
  const [view, setView] = useState<View | null>(() => restoredMap?.view ?? null);
  /**
   * The selection gesture in flight. Two shapes, never a mode for SELECTING
   * itself: shift-drag always selects, and `lassoTool` only changes what it
   * draws. That distinction is why the "no mode toggle" note over `onPointerDown`
   * still holds β€” the thing people would never find behind a mode is selection,
   * and it is still on the bare gesture.
   */
  const [drag, setDrag] = useState<
    | { kind: "rect"; x0: number; y0: number; x1: number; y1: number }
    | { kind: "lasso"; pts: Pt[] }
    | null
  >(null);
  const [lassoTool, setLassoTool] = useState(false);
  /**
   * ⚠ The svg element lives in STATE, not in a ref, and that is load-bearing.
   *
   * `view` starts null, so the FIRST render returns the empty state and there is
   * no <svg> in the tree at all. A `useRef` would still be null when the wheel
   * effect below first ran, and by the time the svg actually mounted the
   * effect's deps (`localPoint`, `kMin`, `kMax`) were all unchanged β€” so React
   * would never re-run it and the wheel listener would never be attached. Wheel
   * zoom would be silently dead on the ordinary path.
   *
   * Holding the element in state makes attachment a consequence of MOUNTING
   * rather than of a dependency happening to change, so the hazard cannot come
   * back. No unit test can see this: the gate is pure TS under node, and a
   * screenshot of a static page has no React in it.
   */
  const [svgEl, setSvgEl] = useState<SVGSVGElement | null>(null);
  /**
   * W37-T35 β€” the tile provider, and whether tiles are working.
   *
   * ⚠ `tiles` starts at the OFFLINE DEFAULT rather than at null, so the basemap paints on the
   * first frame instead of flashing the vector map and then replacing it. The fetch below only
   * ever REPLACES a working default with a configured one.
   */
  const [tiles, setTiles] = useState<TileProvider>(TILES_DEFAULT);
  /** W37-T37 β€” the lookup's batch size and its MEASURED seconds-per-address, both served by the
   *  same provider door as the tiles. Defaults match `routes_geo.py`'s own, so the control works
   *  before the config call lands and keeps working if it never does. */
  const [geoBatch, setGeoBatch] = useState(25);
  const [geoSeconds, setGeoSeconds] = useState(3.3);
  const [tileFails, setTileFails] = useState(0);
  const tilesOk = tileFails < TILE_FAIL_LIMIT;

  useEffect(() => {
    let live = true;
    // β›” A FAILURE HERE IS SILENT ON PURPOSE, and it is the one place in this file where that is
    // right: the answer is a STYLE CHOICE, the default is already correct and already painting,
    // and a person cannot act on "the provider config endpoint is unreachable". The failures that
    // must be loud are the ones that change what the data SAYS, and this changes none.
    fetch("/api/v1/geo/providers", { credentials: "same-origin" })
      .then((r) => (r.ok ? r.json() : null))
      .then((j) => {
        const t = j && j.tiles;
        if (!live || !t || typeof t.url !== "string" || !t.url) return;
        setTiles({
          url: t.url,
          attribution: String(t.attribution || TILES_DEFAULT.attribution),
          attributionUrl: String(t.attributionUrl || TILES_DEFAULT.attributionUrl),
          maxZoom: Number(t.maxZoom) > 0 ? Number(t.maxZoom) : TILES_DEFAULT.maxZoom,
        });
        const gc = j.geocode;
        if (gc) {
          if (Number(gc.maxBatch) > 0) setGeoBatch(Number(gc.maxBatch));
          if (Number(gc.secondsPerAddress) > 0) setGeoSeconds(Number(gc.secondsPerAddress));
        }
        // ⭐ ITEM 7 β€” which travel modes this deployment can actually answer. Unlike the tiles
        // above, a wrong answer here is not a style choice, so the offer is taken from the server
        // and the defaults are only the pre-arrival stand-in.
        const offered = Array.isArray(j.route?.modes) ? j.route.modes : null;
        if (offered) {
          const clean = offered
            .filter((m: { key?: unknown }) => m && (m.key === "driving" || m.key === "walking"))
            .map((m: { key: TravelMode; label?: unknown; available?: unknown }) => ({
              key: m.key,
              label: String(m.label || (m.key === "walking" ? "Walking" : "Driving")),
              available: m.available !== false,
            }));
          if (clean.length) setTravelModes(clean);
        }
      })
      .catch(() => {});
    return () => {
      live = false;
    };
  }, []);
  const panRef = useRef<{ x: number; y: number; tx: number; ty: number } | null>(null);
  /** A finished drag must not also read as a click on the pin underneath β€” the
   *  kanban card's lesson (viewModes.tsx), same fix. */
  const movedRef = useRef(false);
  /** Where a gesture began, in CLIENT pixels, so `onPointerMove` can take the pointer capture
   *  only once it has become a drag. See the block in `onPointerDown` (W38-T09). */
  const downRef = useRef<{ id: number; cx: number; cy: number } | null>(null);
  /** Once the user has zoomed or panned, a data change must NOT yank the view
   *  back. Before that, refitting on new data is the helpful behaviour.
   *  R10 β€” A RESTORED VIEWPORT COUNTS AS TOUCHED, so the auto-fit leaves it alone. `Fit` still
   *  clears this and re-frames the data, which is the way back from any remembered camera. */
  const touchedRef = useRef(Boolean(restoredMap?.view));

  /* ═════════ R10 β€” THE WRITE HALF. `localStorage` ONLY: this touches no saved view ═════════ */
  const mapStateKey = useMemo(() => mapMemoryKey(tableKey, activeView?.id, applicationId), [tableKey, activeView?.id, applicationId]);
  const mapState = useMemo<MapMemory>(() => ({
    view: view ? { k: view.k, tx: view.tx, ty: view.ty, rot: view.rot } : undefined,
    routeId: activeRouteId,
    navigator: mapNavigator,
  }), [activeRouteId, mapNavigator, view]);
  /**
   * β›” THE UNMOUNT WRITE READS A REF, NEVER THE CLOSURE. A `useEffect(() => () => write(mapState),
   * [])` captures the FIRST render's values, so leaving the Map view would store the camera the map
   * OPENED with rather than the one the person left it at β€” a persistence bug that looks exactly
   * like no persistence at all, because the stored value is always the fitted default.
   */
  const mapStateLatest = useRef<{ key: string | null; state: MapMemory }>({ key: mapStateKey, state: mapState });
  useEffect(() => {
    mapStateLatest.current = { key: mapStateKey, state: mapState };
  });
  useEffect(() => {
    if (!mapStateKey) return;
    const timer = window.setTimeout(() => writeMapMemory(mapStateKey, mapState), MAP_MEMORY_DEBOUNCE_MS);
    return () => window.clearTimeout(timer);
  }, [mapState, mapStateKey]);
  useEffect(() => () => {
    const latest = mapStateLatest.current;
    writeMapMemory(latest.key, latest.state);
  }, []);

  /** The view's rows PLUS the ones the user reached past the filter for (owner item 9). */
  const mapRows = useMemo(() => {
    if (routeApplication) {
      const have = new Set(rows.map((row) => row.pid));
      return [...rows, ...(allRows ?? []).filter((row) => selectedPids.has(row.pid) && !have.has(row.pid))];
    }
    if (addedPids.size === 0 || !allRows || allRows.length === 0) return rows;
    const have = new Set(rows.map((r) => r.pid));
    const extra = allRows.filter((r) => addedPids.has(r.pid) && !have.has(r.pid));
    return extra.length ? [...rows, ...extra] : rows;
  }, [rows, allRows, addedPids, routeApplication, selectedPids]);

  const points = useMemo(() => {
    const out: MapPoint[] = [];
    for (const r of mapRows) {
      const at = rowCoordinates(r, coordinateFields, coordField, sessionCoordinates);
      if (!at) continue;
      const { lat, lon } = at;
      out.push({
        pid: r.pid,
        title: String(r[field.key] ?? ""),
        p: project(lon, lat),
        lat,
        lon,
        colorKey: colorField ? String(r[colorField.key] ?? "").trim() : null,
        size: sizeField ? numOrNull(r[sizeField.key]) : null,
        colorVal: colorField ? r[colorField.key] : null,
        sizeVal: sizeField ? r[sizeField.key] : null,
      });
    }
    return out;
  }, [mapRows, field.key, coordinateFields, coordField, sessionCoordinates, colorField, sizeField]);
  /**
   * W46-T26 β€” WHAT EACH STOP IS CALLED. The Route panel used to print a bare ordinal, so the
   * list said nothing about who the driver is visiting. The name lives on the row, not on the
   * route DTO (`visibleStopIds` is a bare `number[]`), so it is carried down from here.
   *
   * β›” BUILT FROM THE ROW BOOK, NOT FROM `points`. `points` holds only rows that survived
   * coordinate validation, so a customer who has never been geocoded is ABSENT from it β€” and
   * that is precisely the stop the address fallback exists to name. `allRows` leads for the same
   * reason the saved-route row resolution takes it: a saved stop may sit outside the current
   * View's filter and must still read as itself rather than as a placeholder.
   *
   * Name and address stay SEPARATE fields rather than one pre-picked string, because the printed
   * route sheet needs both on the same line.
   */
  const routeStopLabels = useMemo(() => {
    const addrKey = coordField?.geocode?.addressField;
    const out: Record<number, { name: string; address: string }> = {};
    const book = allRows && allRows.length ? [...allRows, ...mapRows] : mapRows;
    for (const r of book) {
      if (out[r.pid]) continue;
      out[r.pid] = {
        name: String(r[field.key] ?? "").trim(),
        address: addrKey ? String(r[addrKey] ?? "").trim() : "",
      };
    }
    return out;
  }, [allRows, mapRows, field.key, coordField]);

  /**
   * W46-T19 / CONTRACT C2 β€” the coordinates the Route timer measures from.
   *
   * β›” ROUTENAV CANNOT REACH THESE ON ITS OWN. `stopLabels` carries name and address only, and
   * `NormalizedRouteMapLink` carries `{url,index,start,end,stopIds}` with no lat/lon, so without
   * this prop the timer renders "No drive time yet" forever and C2's whole client half is dead.
   *
   * ⚠ THE SAME DERIVATION AS `activeRouteMaps` (below), deliberately: one rule for what counts as
   * a located stop, so the Maps hand-off and the drive time can never disagree about which stops
   * have a position. Built over the ROW BOOK rather than `points`, because `points` drops every
   * row that failed coordinate validation and a saved stop can sit outside the current filter.
   */
  const routeStopCoords = useMemo(() => {
    const out: Record<number, { lat: number; lon: number }> = {};
    for (const row of (allRows?.length ? allRows : mapRows)) {
      if (out[row.pid]) continue;
      const at = rowCoordinates(row, coordinateFields, coordField, sessionCoordinates);
      if (at) out[row.pid] = { lat: at.lat, lon: at.lon };
    }
    return out;
  }, [allRows, mapRows, coordinateFields, coordField, sessionCoordinates]);

  const loadZones = useCallback(async () => {
    zoneRequestRef.current.controller?.abort();
    const controller = new AbortController();
    const generation = zoneRequestRef.current.generation + 1;
    zoneRequestRef.current = { generation, controller };
    try {
      const res = await routingFetch(zoneCollectionPath(tableKey), {
        credentials: "same-origin",
        signal: controller.signal,
      });
      const body = res.ok ? await res.json().catch(() => null) : null;
      if (!routingAlive.current) return;
      if (zoneRequestRef.current.generation !== generation) return;
      const loadedZones: MapZone[] = Array.isArray(body?.zones) ? body.zones : [];
      setZones(loadedZones);
      setActiveZoneIds(new Set(
        loadedZones.filter((zone) => zone.visible).map((zone) => zone.id)
      ));
    } catch {
      if (controller.signal.aborted) return;
      if (zoneRequestRef.current.generation !== generation) return;
      setZones([]);
      setActiveZoneIds(new Set());
    }
  }, [tableKey, routingFetch]);
  useEffect(() => { void loadZones(); }, [loadZones]);
  const loadNamedRoutes = useCallback(async () => {
    routeRequestRef.current.controller?.abort();
    const controller = new AbortController();
    const generation = routeRequestRef.current.generation + 1;
    routeRequestRef.current = { generation, controller };
    try {
      const res = await routingFetch(routeInventoryPath(), {
        credentials: "same-origin",
        signal: controller.signal,
      });
      const body = res.ok ? await res.json().catch(() => null) : null;
      if (!routingAlive.current) return;
      if (routeRequestRef.current.generation !== generation) return;
      setRoutesLoaded(true);
      if (!res.ok || !Array.isArray(body?.routes)) {
        setRoutesLoadError(true);
        return;
      }
      setRoutesLoadError(false);
      setNamedRoutes(body.routes);
      if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
    } catch {
      if (controller.signal.aborted) return;
      setRoutesLoaded(true);
      setRoutesLoadError(true);
      /* Keep the last honest Route navigation when a refresh is temporarily unavailable. */
    }
  }, [routingFetch]);
  const loadRouteDeliveryRecipients = useCallback(async () => {
    deliveryRecipientRequestRef.current.controller?.abort();
    const controller = new AbortController();
    setRouteDeliveryRecipients(null);
    setDeliveryRecipientError(null);
    const generation = deliveryRecipientRequestRef.current.generation + 1;
    deliveryRecipientRequestRef.current = { generation, controller };
    const result = await fetchRouteDeliveryRecipients(controller.signal, undefined, applicationId);
    if (!routingAlive.current || controller.signal.aborted || deliveryRecipientRequestRef.current.generation !== generation) return;
    if (result.directory) {
      setRouteDeliveryRecipients(result.directory);
      setDeliveryRecipientError(null);
    } else {
      setDeliveryRecipientError(result.error || "Delivery recipients are unavailable.");
    }
  }, [applicationId]);
  useEffect(() => () => {
    zoneRequestRef.current.controller?.abort();
    routeRequestRef.current.controller?.abort();
    deliveryRecipientRequestRef.current.controller?.abort();
  }, []);
  useEffect(() => { void loadNamedRoutes(); }, [loadNamedRoutes]);
  useEffect(() => {
    if (applicationId) onManagedRouteViewState?.({}, applicationId);
  }, [applicationId, onManagedRouteViewState]);
  useEffect(() => {
    if (routePanelOpen) void loadRouteDeliveryRecipients();
  }, [loadRouteDeliveryRecipients, routePanelOpen]);
  useEffect(() => {
    // A managed clause belongs to one saved View. Never carry it into another View's authored state.
    setManagedRouteViewState(null);
    setSelectedRouteIds(new Set());
    setRouteSelectionWarning(null);
  }, [activeView?.id]);
  const routeFilterSignature = useMemo(
    () => routeFilterSignatureOf(activeView?.config?.filters, activeView?.config?.filterConj),
    [activeView?.config?.filterConj, activeView?.config?.filters]
  );
  const routeFilterSignatureRef = useRef({ viewId: activeView?.id || "", signature: routeFilterSignature });
  const filterRestoreSeenRef = useRef(0);
  useEffect(() => {
    const prior = routeFilterSignatureRef.current;
    const viewId = activeView?.id || "";
    // S72-T60: a host restore seeds the ref with its own signature, so it never clears the selection.
    const restored = !!filterRestore && filterRestore.seq !== filterRestoreSeenRef.current &&
      filterRestore.signature === routeFilterSignature;
    if (filterRestore) filterRestoreSeenRef.current = filterRestore.seq;
    const changed = !restored && prior.viewId === viewId && prior.signature !== routeFilterSignature;
    routeFilterSignatureRef.current = { viewId, signature: routeFilterSignature };
    if (!changed || !activeView || selectedRouteIds.size === 0) return;
    void (async () => {
      try {
        const res = await routingFetch("/api/v1/customers/routes/selection", {
          method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ routeIds: [], viewState: activeView.config as unknown as Record<string, unknown> } satisfies RouteSelectionRequest),
        });
        const body = await res.json().catch(() => null) as RouteSelectionResponse | null;
        if (!routingAlive.current) return;
        if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) throw new Error("managed selection refusal");
        setSelectedRouteIds(new Set());
        setManagedRouteViewState(body.viewState);
        onManagedRouteViewState?.(body.viewState, applicationId);
        setRouteSelectionWarning("Route selection cleared because the View filter changed.");
      } catch {
        setRouteSelectionWarning("Route selection could not be cleared after the View filter changed.");
      }
    })();
  }, [activeView, filterRestore, onManagedRouteViewState, routeFilterSignature, selectedRouteIds, routingFetch, applicationId]);
  /**
   * ⭐⭐ W51-T28 / R6 β€” THE WRITE HALF, SPLIT OUT SO THE CONFIRM CAN BE A DIALOG.
   *
   * This body was reached past a `window.confirm` sitting at the top of one async function, and
   * that arrangement cannot survive the change: `window.confirm` blocks the thread and hands back
   * a boolean, while a dialog is a render. There is no way to `await` the dialog without inventing
   * a promise bridge across React state, so the function is CUT INSTEAD OF WRAPPED.
   *
   * β›”β›” THE NAME IS LOAD-BEARING, AND NOT FOR READABILITY. `verify_w44_map_routes.py`'s
   * `managed-route-callback` leg slices this file between the `toggleNamedRoute` declaration and
   * the `moveNamedRouteStop` one, then asserts that `onManagedRouteViewState?.(...)` fires AFTER
   * the `body?.managedBy !== "loopable"` refusal. Splitting the function moved that whole sequence
   * out of the slice, and the leg went red on code whose logic had not changed a line. The
   * extracted half therefore keeps the `toggleNamedRoute` PREFIX, so the slice opens on this
   * function rather than on the entry below it and still contains the whole toggle path. Rename
   * this and that gate, which this ticket does not own, goes red again for the same non-reason.
   *
   * β›”β›” AND THE PROSE HERE MUST NOT SPELL THE ANCHORS THE WAY THE GATE SPELLS THEM. That leg
   * slices with a plain `str.find` over the RAW file and strips no comments, so a note quoting its
   * two anchor strings verbatim, `const` keyword and all, is found BEFORE the real declarations
   * and yields a 33-character slice. That is exactly how this comment reddened the gate it was
   * written to explain, which is why the two names above appear WITHOUT the keyword in front.
   *
   * β›” `isAdding` AND `next` ARE RECOMPUTED HERE, NOT PASSED IN, and that is the trap this note
   * exists for. The pending route waits in state across at least one render; a decision captured
   * at the moment the dialog opened could describe a selection that has since changed underneath
   * it. Recomputing from the live `selectedRouteIds` makes the confirmed act the act the user is
   * looking at. There is exactly ONE copy of this body: the ordinary path calls it directly.
   */
  const toggleNamedRouteSelection = useCallback(async (route: MapRouteDto) => {
    const isAdding = !selectedRouteIds.has(route.id);
    const next = toggleRouteSelection(selectedRouteIds, route.id);
    if (!activeView) {
      setRouteSelectionWarning("Select a saved View before adding a route inclusion.");
      return;
    }
    const routeIds = [...next];
    try {
      const request: RouteSelectionRequest = {
        routeIds,
        viewState: managedRouteViewState || (activeView.config as unknown as Record<string, unknown>),
      };
      const res = await routingFetch("/api/v1/customers/routes/selection", {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(request),
      });
      const body = await res.json().catch(() => null) as RouteSelectionResponse | null;
      if (!routingAlive.current) return;
      if (!res.ok || body?.managedBy !== "loopable" || !body.viewState) {
        setRouteSelectionWarning(body && "error" in body ? String((body as { error?: { message?: string } }).error?.message || "Route inclusion could not be changed.") : "Route inclusion could not be changed.");
        return;
      }
      setSelectedRouteIds(next);
      setManagedRouteViewState(body.viewState);
      onManagedRouteViewState?.(body.viewState, applicationId);
      setRouteSelectionWarning(route.outsideFilter && next.has(route.id) ? `${route.name} is included through its managed route group.` : null);
      const pids = namedRoutes.filter((item) => next.has(item.id)).flatMap((item) => item.visibleStopIds);
      /**
       * ⭐⭐ OWNER 2026-08-31 item 1 - UNTICKING A ROUTE UNDOES EVERYTHING TICKING IT DID.
       *
       * Owner: *"When I press clear after I selected the Route that has records not actually a
       * part of the filter. The record stays, only when I change the filter it actually move
       * back."* Confirmed with them: the control is the route's own checkbox, and the records
       * stay in the grid AND on the map.
       *
       * β›” THE ADD PATH WROTE THREE STORES AND THE REMOVE PATH CLEARED ONE. Ticking a Route
       * writes (a) the server's managed OR clause, (b) the host row selection, and (c) - once
       * the Route has also been opened - `addedPids`, which is what earns an out-of-filter stop
       * a pin through `mapRows`. Unticking sent `"add"` with the REMAINING routes' pids, and
       * `"add"` is monotone: it can never take a pid back out. So (b) and (c) survived, the
       * record kept its row and its pin, and the next filter edit rebuilt the pipeline from
       * scratch - which is exactly the "only when I change the filter" the owner described.
       *
       * ⚠ ONLY THE PIDS NO SURVIVING ROUTE STILL CLAIMS ARE DROPPED. Two ticked routes sharing
       * a stop must not lose it when one of them is unticked, and a record the person picked by
       * hand is not this callback's to remove either - hence the subtraction is computed
       * against `keep`, and the host selection is rebuilt from what it currently holds rather
       * than replaced by the route union.
       */
      if (isAdding) {
        onSelectPids([...new Set(pids)], "add");
      } else {
        const keep = new Set(pids);
        const dropped = (route.visibleStopIds || []).filter((pid) => !keep.has(pid));
        if (dropped.length) {
          const gone = new Set(dropped);
          onSelectPids([...selectedPids].filter((pid) => !gone.has(pid)), "replace");
          setAddedPids((prev) => {
            if (![...gone].some((pid) => prev.has(pid))) return prev;
            const remaining = new Set(prev);
            for (const pid of gone) remaining.delete(pid);
            return remaining;
          });
          for (const pid of gone) routeAddedRef.current.delete(pid);
        }
        // The opened Route detail is armed from `activeNamedRoute`; leaving the arming key set
        // would refuse to re-arm this Route on a later tick, because the signature would match.
        if (armedRouteRef.current.startsWith(`${route.id}:`)) armedRouteRef.current = "";
      }
    } catch { setRouteSelectionWarning("Route inclusion could not be changed."); }
  }, [activeView, managedRouteViewState, namedRoutes, onManagedRouteViewState, onSelectPids, selectedPids, selectedRouteIds, routingFetch, applicationId]);
  /**
   * The ENTRY point. Ticking a route that the View's own filter excludes is the one branch that
   * asks first: the inclusion widens what the grid shows, so the person is told before it happens.
   * Everything else goes straight through to the write above.
   */
  const toggleNamedRoute = useCallback(async (route: MapRouteDto) => {
    const isAdding = !selectedRouteIds.has(route.id);
    if (isAdding && route.outsideFilter) {
      setPendingRouteInclude(route);
      return;
    }
    await toggleNamedRouteSelection(route);
  }, [toggleNamedRouteSelection, selectedRouteIds]);
  const confirmPendingRouteInclude = useCallback(() => {
    const route = pendingRouteInclude;
    if (!route) return;
    // Cleared BEFORE the dispatch, so a second Enter on a dialog that has not yet unmounted
    // cannot post the same inclusion twice.
    setPendingRouteInclude(null);
    void toggleNamedRouteSelection(route);
  }, [toggleNamedRouteSelection, pendingRouteInclude]);
  const moveNamedRouteStop = useCallback(async (route: MapRouteDto, customerPid: number, order: number): Promise<string | null> => {
    try {
      const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/stops/move`, {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ customerPid, order }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (res.status === 409 && body?.error?.code === "no_route_stop") return "This route has no matching stop to move.";
      if (!res.ok) return body?.error?.message || "The stop order could not be changed.";
      const routeUpdate = body?.route as MapRouteDto | undefined;
      if (routeUpdate) setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
        ? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
        : item));
      return null;
    } catch { return "The stop order could not be changed."; }
  }, [routingFetch]);

  const updateNamedRoute = useCallback(async (
    route: MapRouteDto, patch: MapRouteUpdate
  ): Promise<string | null> => {
    const actionAllowed = "starred" in patch
      ? route.capabilities?.star === true
      : route.capabilities?.rename === true;
    if (!actionAllowed)
      return "This Route is read-only.";
    try {
      const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
        method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(patch),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be updated.";
      const routeUpdate = body?.route as MapRouteDto | undefined;
      if (!routeUpdate) return "The Route update returned no Route.";
      setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
        ? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
        : item));
      return null;
    } catch { return "The Route could not be updated."; }
  }, [routingFetch]);

  const deleteNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
    if (route.capabilities?.delete !== true)
      return "This Route is read-only.";
    try {
      const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}`, {
        method: "DELETE", credentials: "same-origin",
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be deleted.";

      const nextSelected = new Set(selectedRouteIds);
      const removedSelection = nextSelected.delete(route.id);
      setNamedRoutes((current) => current.filter((item) => item.id !== route.id));
      setCreatedRoute((current) => current?.id === route.id ? null : current);
      setSelectedRouteIds(nextSelected);
      if (activeRouteId === route.id) setActiveRouteId(null);
      setRoutePinPrompt(null);
      setRoutePinNotice(null);

      if (removedSelection && activeView) {
        try {
          const selectionRes = await routingFetch("/api/v1/customers/routes/selection", {
            method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              routeIds: [...nextSelected],
              viewState: managedRouteViewState || (activeView.config as unknown as Record<string, unknown>),
            } satisfies RouteSelectionRequest),
          });
          const selectionBody = await selectionRes.json().catch(() => null) as RouteSelectionResponse | null;
          if (!routingAlive.current) return "This Routing App is no longer open.";
          if (!selectionRes.ok || selectionBody?.managedBy !== "loopable" || !selectionBody.viewState)
            throw new Error("managed selection refusal");
          setManagedRouteViewState(selectionBody.viewState);
          onManagedRouteViewState?.(selectionBody.viewState, applicationId);
          setRouteSelectionWarning(null);
        } catch {
          setRouteSelectionWarning("The Route was deleted, but its View inclusion could not be cleared.");
        }
      }
      return null;
    } catch { return "The Route could not be deleted."; }
  }, [activeRouteId, activeView, managedRouteViewState, onManagedRouteViewState, selectedRouteIds, routingFetch, applicationId]);

  const requestRoutePinMembership = useCallback((customerPid: number, title: string) => {
    setRoutePinNotice(null);
    if (!activeNamedRoute) {
      setRoutePinPrompt(null);
      setRoutePinNotice("Open a route first.");
      return;
    }
    if (!activeNamedRoute.permission.canEdit) {
      setRoutePinPrompt(null);
      setRoutePinNotice("This Route is read-only.");
      return;
    }
    const isMember = activeNamedRoute.visibleStopIds.includes(customerPid);
    setRoutePinPrompt({
      routeId: activeNamedRoute.id,
      customerPid,
      title: title || `Record ${customerPid}`,
      present: !isMember,
    });
  }, [activeNamedRoute]);

  const confirmRoutePinMembership = useCallback(async () => {
    const prompt = routePinPrompt;
    if (!prompt || routePinBusy) return;
    setRoutePinBusy(true);
    setRoutePinNotice(null);
    try {
      const res = await routingFetch(
        `/api/v1/customers/routes/${encodeURIComponent(prompt.routeId)}/stops/membership`,
        {
          method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ customerPid: prompt.customerPid, present: prompt.present }),
        }
      );
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (!res.ok) {
        setRoutePinNotice(body?.error?.message || body?.detail?.message || "The Route stop could not be changed.");
        return;
      }
      const routeUpdate = body?.route as MapRouteDto | undefined;
      if (!routeUpdate) {
        setRoutePinNotice("The Route stop update returned no Route.");
        return;
      }
      setNamedRoutes((current) => current.map((item) => item.id === routeUpdate.id
        ? { ...item, ...routeUpdate, folderId: item.folderId, navOrder: item.navOrder }
        : item));
      setRoutePinPrompt(null);
      setRoutePinNotice(`${prompt.title} was ${prompt.present ? "added to" : "removed from"} ${routeUpdate.name}.`);
    } catch {
      setRoutePinNotice("The Route stop could not be changed.");
    } finally {
      setRoutePinBusy(false);
    }
  }, [routePinBusy, routePinPrompt, routingFetch]);

  const activeZones = useMemo(
    () => (zones || []).filter((zone) => zone.visible && activeZoneIds.has(zone.id)),
    [zones, activeZoneIds]
  );
  const activeZonePids = useMemo(() => {
    const pids = new Set<number>();
    for (const zone of activeZones) for (const pid of zone.memberships || []) pids.add(pid);
    return pids;
  }, [activeZones]);
  const routeSources = useMemo<MapRouteSource[]>(() => [
    { id: "selection", label: "Current selection", pids: routeSourceStopIds(selectedPids) },
    // β›” HOTFIX 2026-08-31, owner instruction: *"when I create a new route and I select
    // 'Selected Zones' it still selects literally everything in the zone. it shouldn't, it should
    // be scoped to the View's current Filter as well. So its always Filter and then what is in the
    // zone."*
    //
    // A Zone's `memberships` is the WHOLE zone: it is computed server-side against the table
    // (`route_system.zone_members` over the permission-scoped rows), never against the View the
    // person is looking at. Offering that set raw meant every filter they had just set was
    // discarded the moment they picked this source. The source is now FILTER ∩ ZONE, and it is
    // walked in `rows` order rather than membership order so the stop order matches the grid
    // exactly the way "Current filtered records" below already does.
    { id: "zones", label: "Selected Zones",
      pids: routeSourceStopIds(rows.filter((row) => activeZonePids.has(row.pid)).map((row) => row.pid)) },
    // ⭐ W47-T06 / instruction 7. THIS IS A MOVE, NOT A NEW QUERY. `rows` is exactly what the
    // retired "Select all N filtered records" button read, so the picker now offers the same
    // capability in the one place a person is already choosing what the Route is made of. The
    // button and its handler were deleted together, so nothing dangles behind it.
    { id: "filtered", label: "Current filtered records",
      pids: routeSourceStopIds(rows.map((row) => row.pid)) },
  ], [activeZonePids, selectedPids, rows]);
  const createNamedRoute = useCallback(async (name: string, source: MapRouteSource): Promise<string | null> => {
    if (!source.pids.length) return "Choose a Route source with at least one customer.";
    try {
      const res = await routingFetch("/api/v1/customers/routes", {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, stops: source.pids, ...(activeView ? { sourceViewId: activeView.id } : {}) }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || "The Route could not be created.";
      if (body?.route) {
        setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder));
        setCreatedRoute(body.route as MapRouteDto);
        await loadNamedRoutes();
      }
      return null;
    } catch { return "The Route could not be created."; }
  }, [activeView, loadNamedRoutes, routingFetch]);
  const duplicateNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
    if (route.capabilities?.duplicate !== true)
      return "This Route cannot be duplicated.";
    try {
      const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/duplicate`, {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: `${route.name} copy` }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be duplicated.";
      if (!body?.route) return "The duplicate returned no Route.";
      setNamedRoutes((current) => [...current, body.route].sort((a, b) => a.navOrder - b.navOrder));
      setCreatedRoute(body.route as MapRouteDto);
      await loadNamedRoutes();
      return null;
    } catch { return "The Route could not be duplicated."; }
  }, [loadNamedRoutes, routingFetch]);
  const shareNamedRoute = useCallback(async (route: MapRouteDto): Promise<string | null> => {
    if (route.capabilities?.share !== true)
      return "Only the Route owner can share this Route.";
    try {
      const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/share-ready`, {
        method: "POST", credentials: "same-origin",
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "Sharing could not be opened.";
      window.dispatchEvent(new CustomEvent("aios:share-open", {
        detail: { kind: body?.kind || "field", id: body?.id || route.shareId, label: body?.label || route.name },
      }));
      return null;
    } catch { return "Sharing could not be opened."; }
  }, [routingFetch]);
  const moveNamedRoute = useCallback(async (route: MapRouteDto, folderId: string | null): Promise<string | null> => {
    try {
      const res = await routingFetch(`/api/v1/customers/routes/${encodeURIComponent(route.id)}/folder`, {
        method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ folderId }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route could not be moved.";
      if (body?.route) setNamedRoutes((current) => current.map((item) => item.id === route.id ? body.route : item));
      if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
      return null;
    } catch { return "The Route could not be moved."; }
  }, [routingFetch]);
  const reorderNamedRoutes = useCallback(async (order: string[]): Promise<string | null> => {
    try {
      const res = await routingFetch("/api/v1/customers/routes/reorder", {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ order }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route order could not be saved.";
      await loadNamedRoutes();
      return null;
    } catch { return "The Route order could not be saved."; }
  }, [loadNamedRoutes, routingFetch]);
  const createNamedRouteFolder = useCallback(async (name: string, parent: string | null): Promise<string | null> => {
    try {
      const res = await routingFetch("/api/v1/customers/route-folders", {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, parent }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be created.";
      if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
      return null;
    } catch { return "The folder could not be created."; }
  }, [routingFetch]);
  const updateNamedRouteFolder = useCallback(async (
    folder: MapRouteFolderDto, patch: { name?: string; parent?: string | null }
  ): Promise<string | null> => {
    try {
      const res = await routingFetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, {
        method: "PATCH", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(patch),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be updated.";
      if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
      return null;
    } catch { return "The folder could not be updated."; }
  }, [routingFetch]);
  const deleteNamedRouteFolder = useCallback(async (folder: MapRouteFolderDto): Promise<string | null> => {
    try {
      const res = await routingFetch(`/api/v1/customers/route-folders/${encodeURIComponent(folder.id)}`, {
        method: "DELETE", credentials: "same-origin",
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder could not be deleted.";
      if (Array.isArray(body?.folders)) setRouteFolders(body.folders);
      await loadNamedRoutes();
      return null;
    } catch { return "The folder could not be deleted."; }
  }, [loadNamedRoutes, routingFetch]);
  const reorderNamedRouteFolders = useCallback(async (order: string[]): Promise<string | null> => {
    try {
      const res = await routingFetch("/api/v1/customers/route-folders/reorder", {
        method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ order }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The folder order could not be saved.";
      await loadNamedRoutes();
      return null;
    } catch { return "The folder order could not be saved."; }
  }, [loadNamedRoutes, routingFetch]);
  const zoneEditor = useMemo(
    () => (zones || []).find((zone) => zone.id === zoneEditorId) || null,
    [zones, zoneEditorId]
  );
  const beginNewZone = useCallback(() => {
    setZoneEditorId("");
    setZoneName("");
    setZoneColor(ZONE_COLOR_CHOICES[0].value);
    setZoneDrawShape("polygon");
    setDrawnZoneGeometry(null);
    setZoneKeyboardDraft(null);
    setZoneErr(null);
    setZoneEditorOpen(true);
  }, []);
  const beginEditZone = useCallback((zone: MapZone) => {
    setZoneEditorId(zone.id);
    setZoneName(zone.name);
    setZoneColor(zone.color);
    setZoneDrawShape(zone.geometryGeoJson?.type === "Circle" ? "circle" : "polygon");
    setDrawnZoneGeometry(null);
    setZoneKeyboardDraft(null);
    setZoneErr(null);
    setZoneEditorOpen(true);
  }, []);
  /**
   * Zone visibility is a checkbox chooser, not a ctrl-click native multi-select.  A toggle also
   * immediately projects the Zone's durable membership onto the grid selection; removing one
   * Zone preserves records that are still held by another checked Zone.
   */
  const toggleZone = useCallback((zone: MapZone, checked: boolean) => {
    const next = new Set(activeZoneIds);
    if (checked) next.add(zone.id);
    else next.delete(zone.id);
    const stillHeld = new Set<number>();
    for (const item of zones || []) {
      if (!next.has(item.id)) continue;
      for (const pid of item.memberships || []) stillHeld.add(pid);
    }
    const selection = new Set(selectedPids);
    if (checked) for (const pid of zone.memberships || []) selection.add(pid);
    else for (const pid of zone.memberships || []) if (!stillHeld.has(pid)) selection.delete(pid);
    onSelectPids([...selection], "replace");
    setActiveZoneIds(next);
  }, [activeZoneIds, zones, selectedPids, onSelectPids]);
  const zonePolygons = useMemo(() => activeZones.flatMap((zone) => {
    const geometry = zoneGeometryDraft?.id === zone.id
      ? zoneGeometryDraft.geometry
      : zone.geometryGeoJson;
    if (!geometry) return [];
    const polygons = geometry.type === "Polygon"
      ? [geometry.coordinates as number[][][]]
      : geometry.type === "MultiPolygon"
      ? geometry.coordinates as number[][][][]
      : [];
    return polygons.flatMap((polygon, polygonIndex) => polygon.map((ring, ringIndex) => {
      // β›” W46-T28 β€” THE SOURCE INDEX TRAVELS WITH THE POINT. The filter below drops any pair
      // that is not two finite numbers, so a rendered point's position in this array is NOT its
      // position in the stored ring. A vertex drag writes back BY INDEX, and reading the screen
      // index would silently move a different corner the moment one bad pair existed.
      const points = ring
        .map((pair, vertexIndex) => ({ pair, vertexIndex }))
        .filter(({ pair }) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
        .map(({ pair, vertexIndex }) => ({ ...project(pair[0], pair[1]), vertexIndex }));
      const last = points.length - 1;
      const closed = last > 0 && points[0].x === points[last].x && points[0].y === points[last].y;
      return {
        key: `${zone.id}:${polygonIndex}:${ringIndex}`,
        zone,
        geometry,
        polygonIndex,
        ringIndex,
        points,
        // One dot per CORNER. The closing coordinate is the opening one stored twice, so
        // drawing it too would stack two handles on the same pixel and the top one would
        // shadow the other's drag.
        handles: closed ? points.slice(0, last) : points,
      };
    }).filter((ring) => ring.points.length >= 4));
  }), [activeZones, zoneGeometryDraft]);
  const zoneCircles = useMemo(() => activeZones.flatMap((zone) => {
    const geometry = zoneGeometryDraft?.id === zone.id ? zoneGeometryDraft.geometry : zone.geometryGeoJson;
    if (!geometry || geometry.type !== "Circle") return [];
    const center = project(geometry.center[0], geometry.center[1]);
    const latitudeRadians = geometry.center[1] * Math.PI / 180;
    const lonDelta = geometry.radiusMeters / Math.max(1, 111_320 * Math.cos(latitudeRadians));
    const edge = project(geometry.center[0] + lonDelta, geometry.center[1]);
    return [{ zone, geometry, center, radius: Math.abs(edge.x - center.x) }];
  }), [activeZones, zoneGeometryDraft]);

  /**
   * β›”β›” W47-T03 β€” THE FINISHED-BUT-UNSAVED BOUNDARY, PROJECTED SO IT CAN FINALLY BE PAINTED.
   * Owner instruction 20: *"When I click 'Finish zone' under the Zone navigation, the zone just
   * disappear. Only when I save the zone does it actually reappear. This is really bad UI, i was
   * really confused whether I have made the zone or not."*
   *
   * THE CAUSE, EXACTLY. `finishZoneDraft` stores the boundary in `drawnZoneGeometry` and then
   * clears `zoneKeyboardDraft` β€” and `zoneKeyboardDraft` was the ONLY state painting anything.
   * `drawnZoneGeometry` was read by `saveZone` and by the Save button's `title` and by NO render
   * path in this file, so the shape existed, was saveable, and was invisible. The owner was not
   * confused by a subtle state: there was nothing on the screen to be in one.
   *
   * ⭐ IT COVERS THREE GESTURES, NOT THE ONE THE TICKET NAMES. `setDrawnZoneGeometry` also fires
   * from `onPointerUp` when a drag-drawn marquee or lasso closes with the Zone editor open, and
   * that outline was equally unpainted the moment the marquee cleared. One render site, all of
   * them.
   *
   * ⚠ THE PROJECTIONS ARE `zonePolygons`' AND `zoneCircles`' OWN, DELIBERATELY. The geometry is
   * lon/lat (it came out of `unproject(fromScreen(...))`), so this mounts INSIDE
   * `<g transform={tf}>` and holds its ground through every pan, zoom and rotation, exactly as
   * the saved boundary it is about to become does. β›” Do NOT copy the `.cg-zone-keyboard-draft`
   * group's form: that one lives OUTSIDE `tf` on screen coordinates, which is why its clamp
   * takes no zoom argument. Inside `tf` the clamp needs `view.k` or the screen bound goes slack.
   */
  const unsavedZoneShape = useMemo(() => {
    const geometry = drawnZoneGeometry;
    if (!geometry) return null;
    if (geometry.type === "Circle") {
      const center = project(geometry.center[0], geometry.center[1]);
      const latitudeRadians = geometry.center[1] * Math.PI / 180;
      const lonDelta = geometry.radiusMeters / Math.max(1, 111_320 * Math.cos(latitudeRadians));
      const edge = project(geometry.center[0] + lonDelta, geometry.center[1]);
      return { kind: "circle" as const, center, radius: Math.abs(edge.x - center.x) };
    }
    const polygons = geometry.type === "Polygon"
      ? [geometry.coordinates as number[][][]]
      : geometry.type === "MultiPolygon"
        ? geometry.coordinates as number[][][][]
        : [];
    // A pair that is not two finite numbers is dropped rather than projected: `project` would
    // return NaN and one NaN in a `points` list voids the WHOLE polygon, so a single bad vertex
    // would put the screen back exactly where instruction 20 found it.
    const rings = polygons
      .flatMap((polygon) => polygon.map((ring) => ring
        .filter((pair) => Array.isArray(pair) && Number.isFinite(pair[0]) && Number.isFinite(pair[1]))
        .map((pair) => project(pair[0], pair[1]))))
      .filter((ring) => ring.length >= 3)
      .map((ring) => ring.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" "));
    return rings.length ? { kind: "polygon" as const, rings } : null;
  }, [drawnZoneGeometry]);

  /**
   * β›”β›” W46-T28 β€” `pendingGeometry` IS THE FIX FOR "IT WON'T EVEN LET ME SAVE", and it is here
   * rather than in a `useEffect` because React state set in the same tick is not readable from
   * this closure. The Save button commits a still-open click-drawn outline and hands the
   * geometry straight down, so the save does not have to wait a render for `drawnZoneGeometry`.
   */
  const saveZone = useCallback(async (existing?: MapZone, pendingGeometry?: ZoneGeometry) => {
    const geometryGeoJson = pendingGeometry || drawnZoneGeometry || existing?.geometryGeoJson;
    const name = zoneName.trim() || existing?.name || "";
    if (!name || !geometryGeoJson) {
      setZoneErr("Name a Zone and draw its boundary on the map.");
      return;
    }
    if (normalizedCustomerZones && !existing && !activeView?.id) {
      setZoneErr("Open a saved View before creating a Customer Zone.");
      return;
    }
    setZoneBusy(true);
    setZoneErr(null);
    try {
      const res = await routingFetch(existing ? zoneItemPath(tableKey, existing.id) : zoneCollectionPath(tableKey), {
        method: existing ? "PATCH" : "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(zoneMutationPayload(tableKey, existing?.sourceViewId || activeView?.id || null, {
          name,
          color: zoneColor || existing?.color || ZONE_COLOR_CHOICES[0].value,
          geometryGeoJson,
          visible: existing?.visible ?? true,
        })),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (!res.ok) {
        setZoneErr(body?.error?.message || "The Zone could not be saved.");
        return;
      }
      const saved = body?.zone as MapZone | undefined;
      if (saved) {
        setZones((current) => {
          const without = (current || []).filter((zone) => zone.id !== saved.id);
          return [...without, saved].sort((a, b) => a.name.localeCompare(b.name));
        });
        setActiveZoneIds((current) => {
          const next = new Set(current);
          if (saved.visible) next.add(saved.id);
          else next.delete(saved.id);
          return next;
        });
        setZoneEditorId(saved.id);
        setZoneEditorOpen(false);
        if (normalizedCustomerZones) onZoneChanged?.(applicationId);
      }
      setDrawnZoneGeometry(null);
      setZoneName("");
    } catch {
      setZoneErr("The Zone could not be saved.");
    } finally {
      setZoneBusy(false);
    }
  }, [drawnZoneGeometry, zoneName, zoneColor, tableKey, normalizedCustomerZones,
      activeView?.id, onZoneChanged, routingFetch, applicationId]);

  const setZoneVisible = useCallback(async (zone: MapZone, visible: boolean) => {
    setZoneBusy(true);
    setZoneErr(null);
    try {
      const res = await routingFetch(zoneItemPath(tableKey, zone.id), {
        method: "PATCH",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(zoneMutationPayload(tableKey, zone.sourceViewId || activeView?.id || null, { visible })),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (!res.ok) {
        setZoneErr(body?.error?.message || "The Zone visibility could not be updated.");
        return;
      }
      const saved = body?.zone as MapZone | undefined;
      if (saved) {
        setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
        if (!saved.visible && activeZoneIds.has(saved.id)) toggleZone(zone, false);
        if (normalizedCustomerZones) onZoneChanged?.(applicationId);
      }
    } catch {
      setZoneErr("The Zone visibility could not be updated.");
    } finally {
      setZoneBusy(false);
    }
  }, [tableKey, activeZoneIds, toggleZone, activeView?.id, normalizedCustomerZones, onZoneChanged, routingFetch, applicationId]);

  /** Persist a direct boundary drag without re-deriving membership from the current selection. */
  const persistZoneGeometry = useCallback(async (zone: MapZone, geometryGeoJson: ZoneGeometry) => {
    setZoneBusy(true);
    setZoneErr(null);
    try {
      const res = await routingFetch(zoneItemPath(tableKey, zone.id), {
        method: "PATCH",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(zoneMutationPayload(
          tableKey, zone.sourceViewId || activeView?.id || null, { geometryGeoJson },
        )),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (!res.ok) {
        setZoneErr(body?.error?.message || "The Zone boundary could not be saved.");
        return;
      }
      const saved = body?.zone as MapZone | undefined;
      if (saved) {
        setZones((current) => (current || []).map((item) => item.id === saved.id ? saved : item));
        if (normalizedCustomerZones) onZoneChanged?.(applicationId);
      }
    } catch {
      setZoneErr("The Zone boundary could not be saved.");
    } finally {
      setZoneBusy(false);
    }
  }, [tableKey, activeView?.id, normalizedCustomerZones, onZoneChanged, routingFetch, applicationId]);

  const deleteZone = useCallback(async (zone: MapZone) => {
    setZoneBusy(true);
    setZoneErr(null);
    try {
      const generic = !normalizedCustomerZones;
      const res = await routingFetch(zoneItemPath(tableKey, zone.id), {
        method: "DELETE",
        credentials: "same-origin",
        ...(generic ? {
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ tableKey }),
        } : {}),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (!res.ok) {
        setZoneErr(body?.error?.message || body?.detail?.message || "The Zone could not be deleted.");
        return;
      }
      setZones((current) => (current || []).filter((item) => item.id !== zone.id));
      setActiveZoneIds((current) => {
        const next = new Set(current);
        next.delete(zone.id);
        return next;
      });
      setZoneEditorId("");
      setZoneEditorOpen(false);
      if (normalizedCustomerZones) onZoneChanged?.(applicationId);
    } catch {
      setZoneErr("The Zone could not be deleted.");
    } finally {
      setZoneBusy(false);
    }
  }, [normalizedCustomerZones, onZoneChanged, tableKey, routingFetch, applicationId]);

  // The fit is the INITIAL view, not the projection (see mapProjection.ts).
  const fit = useMemo(
    () => fitView(points.map((p) => p.p), VIEW_W, VIEW_H) ?? (routeApplication
      ? fitView([{ x: 0, y: 0 }, { x: WORLD, y: WORLD }], VIEW_W, VIEW_H)
      : null),
    [points, routeApplication]
  );
  useEffect(() => {
    if (!fit) return;
    if (!touchedRef.current || view == null) setView(fit);
    // `view` is deliberately absent from the deps: this effect exists to seed
    // and re-fit, and re-running it on every pan would fight the user for the
    // camera.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fit]);

  /* ═══════════════ W51-T28 / C8 β€” ESCAPE CLOSES THE MAP'S OWN PANELS ═══════════════════════
   *
   * β›” THE TWO CLOSE ACTIONS ARE NAMED CALLBACKS, AND THE `Back` BUTTONS CALL THE SAME ONES.
   * Escape that does something slightly different from the visible close is a second behaviour
   * wearing the first one's name; sharing the callback makes "Escape does what Back does" a
   * property of the code rather than a claim about it.
   *
   * ⚠ THE `active` FLAGS MUST MATCH THE RENDER CONDITIONS, INCLUDING THE EMPTY STATE. This
   * component returns `.cg-mode-empty` early when there is no camera and no fit, and that branch
   * renders none of these panels. A claim on Escape from a panel nobody can see would swallow the
   * key from whatever IS on screen, so `mapCanvasMounted` is part of both flags. The two panel
   * expressions are hoisted here rather than duplicated: the render sites below read these same
   * constants, so the flag and the panel cannot drift apart.
   *
   * ⭐ THE TOPMOST-WINS ORDER IS NOT CONFIGURED ANYWHERE, ON PURPOSE. `useEscapeClose` keeps ONE
   * push-ordered stack, and `ConfirmDialog` joins it when it opens, i.e. after the panel that
   * opened it. So Escape closes the dialog first and the panel underneath on the second press,
   * with no priority number, no z-index and no second listener involved.
   *
   * ⚠ `cancelEditFirst` STAYS AT ITS DEFAULT FALSE. These are panels holding a Zone-name input
   * and a search box; opting in would turn every one of those into a two-Escape close.
   */
  const mapCanvasMounted = view != null && fit != null;
  const zoneChooserPanelOpen = zones !== null && mapNavigator === "zones" && !zoneEditorOpen;
  const zoneEditorPanelOpen = zones !== null && mapNavigator === "zones" && zoneEditorOpen;
  const closeZoneChooser = useCallback(() => setZoneNavigatorOpen(false), []);
  const closeZoneEditor = useCallback(() => {
    setZoneErr(null);
    setZoneEditorOpen(false);
  }, []);
  useEscapeClose(mapCanvasMounted && zoneChooserPanelOpen, closeZoneChooser);
  useEscapeClose(mapCanvasMounted && zoneEditorPanelOpen, closeZoneEditor);

  /**
   * W37-T35 β€” HOW FAR IN THE CAMERA MAY GO, and the answer now depends on what is under the pins.
   *
   * `BASEMAP_DETAIL_K` is an HONESTY limit on the VENDORED geometry: past it you are magnifying a
   * generalised polygon and learning nothing. Real tiles have their own resolution, several orders
   * further in, so keeping that cap while a street map is loaded would be a limit with no subject.
   *
   * ⚠ `zoomLimits`' second term (`fitK * 60`) also binds, and it binds FIRST: a US-wide fit sits
   * near k=1.36, so 60x lands around tile zoom 10 and the user never reaches a street whatever
   * `detailK` says. So the tile branch computes its ceiling from the PROVIDER's own max zoom
   * rather than taking that helper's answer. `kMin` is still the helper's, unchanged.
   */
  const { kMin, kMax } = useMemo(() => {
    if (!fit) return { kMin: 1, kMax: 1 };
    const vector = zoomLimits(fit.k, VIEW_H, BASEMAP_DETAIL_K);
    if (!tilesOk) return vector;
    return { kMin: vector.kMin, kMax: Math.max(fit.k, kForTileZoom(tiles.maxZoom)) };
  }, [fit, tilesOk, tiles.maxZoom]);

  /**
   * W37-T35 β€” WHICH TILES COVER WHAT IS ON SCREEN.
   *
   * ⭐ THE REASON THIS IS ~20 LINES AND NOT A LIBRARY: `mapProjection.project` is already fixed Web
   * Mercator onto a 0..WORLD square, which IS the tile scheme's own coordinate system scaled by
   * WORLD. So tile (x, y) at zoom z occupies exactly `[x*S, (x+1)*S] x [y*S, (y+1)*S]` with
   * `S = WORLD / 2^z`, and dropping the images inside the SAME transformed group as the pins makes
   * them pan and zoom in lockstep with the geography. There is no second camera to keep in sync,
   * which is the failure mode a tile library would have been carrying the weight of.
   *
   * ⚠ Clamped to the world, never wrapped. Panning past the antimeridian shows no tiles rather
   * than a second copy of the planet, and the vendored coastline never wrapped either.
   */
  const tileLayer = useMemo(() => {
    if (!view || !tilesOk || !tiles.url) return null;
    const z = Math.max(0, Math.min(tiles.maxZoom, googleZoomForK(view.k)));
    const n = Math.pow(2, z);
    const S = WORLD / n;
    // ⭐ OWNER ITEM 1 (2026-08-23) β€” ALL FOUR CORNERS, NOT TWO. Two corners describe the world
    // rectangle on screen only while the map is north-up; the moment it carries a bearing the
    // screen rectangle is a rotated QUADRILATERAL in world space, and its top-left corner is no
    // longer its minimum on either axis. Taking two would have left a triangular wedge of the
    // frame with no tiles under it at every bearing that is not a multiple of 90 degrees.
    // ⚠ THE BUDGET IS NOT THE BINDING CONSTRAINT, measured rather than assumed: the frame is
    // 1000x620 units at ~1.08 CSS px each, and `googleZoomForK` targets ~256 CSS px per tile, so
    // a north-up frame asks for roughly 5x4 tiles. The worst bearing (45 degrees) grows the
    // bounding box to ~1145x1145 units, i.e. ~5x5 tiles. Both are an order of magnitude under
    // `TILE_BUDGET`.
    const corners = [
      fromScreen({ x: 0, y: 0 }, view),
      fromScreen({ x: VIEW_W, y: 0 }, view),
      fromScreen({ x: 0, y: VIEW_H }, view),
      fromScreen({ x: VIEW_W, y: VIEW_H }, view),
    ];
    const minX = Math.min(...corners.map((c) => c.x));
    const maxX = Math.max(...corners.map((c) => c.x));
    const minY = Math.min(...corners.map((c) => c.y));
    const maxY = Math.max(...corners.map((c) => c.y));
    const x0 = Math.max(0, Math.floor(minX / S));
    const x1 = Math.min(n - 1, Math.floor(maxX / S));
    const y0 = Math.max(0, Math.floor(minY / S));
    const y1 = Math.min(n - 1, Math.floor(maxY / S));
    if (x1 < x0 || y1 < y0) return null;
    // One tile-pixel of overlap. Tile edges land on fractional device pixels at most zooms, and
    // without it the seams paint as a faint grid across the whole basemap.
    const over = S / 256;
    const items: { key: string; x: number; y: number; s: number; href: string }[] = [];
    for (let ty = y0; ty <= y1 && items.length < TILE_BUDGET; ty++) {
      for (let tx = x0; tx <= x1 && items.length < TILE_BUDGET; tx++) {
        items.push({
          key: `${z}/${tx}/${ty}`,
          x: tx * S,
          y: ty * S,
          s: S + over,
          href: tiles.url
            .replace("{z}", String(z))
            .replace("{x}", String(tx))
            .replace("{y}", String(ty)),
        });
      }
    }
    return {
      z,
      items,
      bed: { x: x0 * S, y: y0 * S, w: (x1 - x0 + 1) * S, h: (y1 - y0 + 1) * S },
    };
  }, [view, tilesOk, tiles.url, tiles.maxZoom]);

  /** Colour buckets, in first-seen order so the legend is stable. */
  const colorBuckets = useMemo(() => {
    if (!colorField) return null;
    const order: string[] = [];
    const counts = new Map<string, number>();
    for (const p of points) {
      const k = p.colorKey ?? "";
      if (!counts.has(k)) {
        counts.set(k, 0);
        order.push(k);
      }
      counts.set(k, (counts.get(k) ?? 0) + 1);
    }
    const named = order.filter((k) => k !== "");
    const swatch = new Map<string, { fill: string; line: string }>();
    named.forEach((k, i) => swatch.set(k, i < SERIES.length ? SERIES[i] : OVERFLOW));
    return {
      order,
      counts,
      swatch,
      overflow: Math.max(0, named.length - SERIES.length),
    };
  }, [colorField, points]);

  /** The size field's observed range across MAPPED points (not the whole table:
   *  the legend must describe the picture actually on screen). */
  const sizeRange = useMemo(
    () => bubbleSizeRange(points.map((p) => p.size), !!sizeField),
    [sizeField, points]
  );

  /** A coarse pointer means a phone or tablet, where Google's free URL takes 3
   *  waypoints rather than 9. A media query, not user-agent sniffing. */
  const coarsePointer = useMemo(
    () =>
      typeof window !== "undefined" &&
      typeof window.matchMedia === "function" &&
      window.matchMedia("(pointer: coarse)").matches,
    []
  );

  const activeRouteMaps = useMemo(() => {
    if (!activeNamedRoute) return { links: [], missingStopIds: [], refusal: null };
    const wanted = new Set(activeNamedRoute.visibleStopIds);
    const located = [] as { pid: number; lat: number; lon: number }[];
    for (const row of (allRows?.length ? allRows : mapRows)) {
      if (!wanted.has(row.pid)) continue;
      const at = rowCoordinates(row, coordinateFields, coordField, sessionCoordinates);
      if (at) located.push({ pid: row.pid, lat: at.lat, lon: at.lon });
    }
    return normalizedRouteMapLinks(activeNamedRoute.visibleStopIds, located, coarsePointer);
  }, [activeNamedRoute, allRows, coarsePointer, coordinateFields, coordField, mapRows, sessionCoordinates]);
  const activeRouteMapsRefusal = activeRouteMaps.missingStopIds.length
    ? `${activeRouteMaps.missingStopIds.length.toLocaleString()} Route stop${activeRouteMaps.missingStopIds.length === 1 ? " has" : "s have"} no map location. Add coordinates before opening Maps links.`
    : activeRouteMaps.refusal;

  /** Selected pins that can actually be routed, in a STABLE order (by pid) β€”
   *  a Set's iteration order must not be what decides a route. */
  const customerRoutable = useMemo(
    () =>
      selectedPids.size < 2
        ? []
        : points
            .filter((p) => selectedPids.has(p.pid) && isPlottable(p.lat, p.lon))
            .sort((a, b) => a.pid - b.pid),
    [points, selectedPids]
  );
  useEffect(() => {
    if (!recordsPending && routeOn && customerRoutable.length < 2) {
      setRouteOn(false);
      setRouteOrder(null);
      setRoad(null);
      setRoadErr(null);
    }
  }, [routeOn, customerRoutable.length, recordsPending]);

  /**
   * ⭐⭐ OWNER ITEM 3 (2026-08-23) β€” OPENING **Route** ROUTES THE VIEW.
   *
   * Owner: *"I have to select first before the route populates? I want it so that by default,
   * when I click the Route button. It already selects everything in that View as the route."*
   * So opening the panel with nothing chosen takes the view's own pins as the cohort and solves
   * them, instead of showing an empty planner and a sentence about shift-clicking.
   *
   * β›” IT ARMS THE LOCAL SOLVE AND **NOT** THE ROAD REQUEST, which is R3 honoured rather than
   * bent. R3 forbids SPENDING a routing request on anything but a click; `planRoute` is local
   * arithmetic that costs nothing and runs in single-digit milliseconds at the cap, so the
   * sequence, the distance estimate and the drawn line are there on open, and the provider is
   * asked only when somebody presses Driving route. `askRoadRef` is deliberately not set here.
   *
   * β›” AND IT NEVER OVERRIDES A CHOICE ALREADY MADE. A person who selected pins and then opened
   * the panel keeps their selection; the auto-fill is for the empty case, which is the one the
   * owner is describing.
   *
   * ⚠ ONCE PER OPENING, VIA A REF. `points` and `selectedPids` both move constantly (a pan does
   * not, but an edit does), and an effect that re-ran on them would keep dragging the selection
   * back to the whole view every time the user narrowed it by hand.
   * ⚠ AND THE REF IS ARMED ONLY WHEN THERE WERE PINS TO TAKE. Opening the panel while the rows
   * are still loading would otherwise consume the one shot on an empty map.
   *
   * β›” CAPPED AT `ROUTE_STOP_CAP`, IN THE VIEW'S OWN ORDER, AND SAID OUT LOUD. `rows` reaches
   * this component through `useVisibleRows`' filter -> search -> SORT -> group pipeline, so
   * "the first N" means the first N as the view is sorted -- the user's own ranking, which is
   * the only ranking this surface has. The owner asked for "the top SKU"; the map has no SKU,
   * and inventing one would be a plausible order nobody chose. Bulk selection now remains an
   * explicit action, so simply opening the route rail cannot alter the current selection.
   */
  /**
   * Opening Routes is intentionally inert.  This explicitly labelled control is the sole bulk
   * selection door: it takes every record matched by the current View (never a hidden cap of
   * mapped pins) and then starts the local planner.
   */

  /** The depot joins BOTH index-parallel arrays below at position zero, and only there. */
  const depotPoint = useMemo((): MapPoint | null => {
    if (!depot || !isPlottable(depot.lat, depot.lon)) return null;
    return {
      pid: DEPOT_PID,
      title: "Depot",
      p: project(depot.lat, depot.lon),
      lat: depot.lat,
      lon: depot.lon,
      colorKey: null,
      size: null,
      colorVal: null,
      sizeVal: null,
    };
  }, [depot]);
  const routable = useMemo(
    () => depotPoint ? [depotPoint, ...customerRoutable] : customerRoutable,
    [depotPoint, customerRoutable]
  );
  /** Selected records with no usable coordinate. Counted and shown, never
   *  folded silently into the stop total ([[no-unverifiable-aggregates]]). */
  const unroutable = selectedPids.size - customerRoutable.length;

  /** Selected records with no usable coordinate, BY NAME. W37-T36: the chip used to give a bare
   *  count, which tells you that something is missing and not which visit you are about to fail to
   *  make. Three names inline, the rest on the tooltip, so the bar cannot be swamped by a big
   *  selection while the full list stays one hover away. */
  const unroutableNames = useMemo(() => {
    // ⚠ Read from `rows` and NOT from `points`: a record with no coordinate never becomes a point
    // in the first place, so filtering the pin list for unplottable pins finds exactly nothing.
    // That mistake would have shipped a chip whose count said 4 and whose names said none.
    const ok = new Set(customerRoutable.map((p) => p.pid));
    return mapRows
      .filter((r) => selectedPids.has(r.pid) && !ok.has(r.pid))
      .map((r) => String(r[field.key] ?? "").trim() || `#${r.pid}`);
  }, [mapRows, field.key, selectedPids, customerRoutable]);

  const plan = useMemo(() => {
    if (!routeOn || customerRoutable.length < 2) return null;
    const stops: GeoStop[] = routable.map((p) => ({ lat: p.lat, lon: p.lon }));
    // Default origin: the WESTERNMOST stop. Deterministic, stable while the user
    // pans, and sayable out loud β€” unlike "whatever ended up at index 0". The
    // picker below overrides it.
    let start = 0;
    if (!depotPoint) {
      for (let i = 1; i < routable.length; i++)
        if (routable[i].lon < routable[start].lon) start = i;
      if (routeStartPid != null) {
        const i = routable.findIndex((p) => p.pid === routeStartPid);
        if (i >= 0) start = i;
      }
    }
    const end = !roundTrip && !depotPoint && routeEndPid != null
      ? routable.findIndex((p) => p.pid === routeEndPid) : -1;
    // A selected terminal is part of the solve, not an element moved after it.  The latter can
    // paint a correct-looking endpoint with kilometres calculated for another one.  Round trips
    // clear the terminal before arriving here and retain the established closed-tour planner.
    const planned = end >= 0 && end !== start
      ? endpointRoutePlan(stops, haversineKm, { start, end, roundTrip })
      : planRoute(stops, haversineKm, { start, roundTrip });
    const { order, km } = planned;
    // ⭐⭐ W38-T20 β€” THE HAND-REORDER STAYS IN **INDEX** SPACE, and that is a deliberate change of
    // representation rather than a tidy-up. `stops`, `routable` and `order` are one index space
    // already (`order.map(i => routable[i])` is what zips them back), and the visit NUMBER a
    // record carries is the inverse of a permutation over exactly that space. Rebuilding the
    // sequence out of MapPoints and then recovering indices from it would be a second, silent
    // conversion between the two β€” and W38-T21 prepends a synthetic depot into this same index
    // space, which is far harder to reason about across two representations than one.
    // ⚠ EXACTLY THE OLD BEHAVIOUR: `order` is a permutation of every index and `ordered` was
    // `order.map(i => routable[i])`, so filtering `order` by index-not-seen selects the same
    // stops, in the same sequence, as filtering `ordered` by pid-not-seen did.
    let seq = order;
    // W37-T36 β€” a hand-picked order wins over the planner's, but only for the stops that are still
    // selected. Anything the user has since deselected drops out; anything newly selected is
    // appended in the planner's own order rather than being silently left off the route.
    if (routeOrder) {
      const idxByPid = new Map(
        routable.filter((p) => p.pid !== DEPOT_PID).map((p, i) => [p.pid, depotPoint ? i + 1 : i])
      );
      const picked = routeOrder
        .map((pid) => idxByPid.get(pid))
        .filter((i) => i !== undefined) as number[];
      const seen = new Set(picked);
      seq = [
        ...(depotPoint ? [0] : []),
        ...picked,
        ...order.filter((i) => !seen.has(i) && (!depotPoint || i !== 0)),
      ];
    }
    /**
     * ⭐⭐ W46-T21 / D-469 β€” WHY THE HAND ORDER IS CANONICALISED BEFORE IT IS HASHED.
     *
     * `routeFingerprint`'s canon carries an `h:<handOrder>` term, and the two sides of the
     * staleness comparison disagreed about it STRUCTURALLY, not because anything changed:
     *   at SAVE the planner had solved the order, so `routeOrder` was null and the stored hash
     *   carried `h:` EMPTY; on REOPEN the arming effect sets `routeOrder` to the saved sequence,
     *   so the live hash carried `h:6534,...`. They can never be equal, so EVERY saved route read
     *   Stale forever, including one saved seconds earlier. That is D-469, and the "third term"
     *   it could not isolate is this: the same term, present on one side and absent on the other.
     *
     * β›” THE `h:` TERM IS NOT DELETED, because D-429 depends on it: a genuine HAND edit must still
     * read as not-freshly-solved. Instead it contributes NOTHING when the applied sequence IS the
     * planner's own answer, which is the only case where a hand order carries no information.
     * A real hand edit differs from `order` and keeps its `h:`.
     *
     * ⭐ NO MIGRATION. Shape (ii) - re-hashing at save time with the order actually saved - would
     * have left every already-stored hash permanently mismatched, including the 52 routes stamped
     * 2026-08-23 that D-469 measured.
     *
     * ⚠ TWO OTHER TERMS ARE STILL ASYMMETRIC and this does NOT reach them: the column stores
     * `roundTrip` and `startPid`, and neither reopen path restores them, so a route saved
     * round-trip, or with an explicitly picked origin, still mismatches. Restoring them would
     * flip the map's own round-trip toggle when a route opens, which is a visible behaviour change
     * made for a staleness marker that this file no longer computes at all: W47-T09 deleted the
     * derivation under R9, because it was always false on the shipped UI. Left deliberately, and
     * recorded, for whoever next puts a staleness mark on screen.
     */
    const seqEqualsOrder = seq.length === order.length && seq.every((v, i) => v === order[i]);
    const ordered = seq.map((i) => routable[i]);
    // β›”β›” THE PERMUTATION IS NOT THE RANK (A25 / A44). `seq[i]` is WHICH STOP is visited i-th;
    // the number a record carries is the other way round, and `routeRanks` is the one inversion.
    // It is called HERE, in the shipped path, and not only in the gate: a tested function the
    // product does not use guards nothing (`paintedRadius`'s docstring is this repo's record of
    // that, and the wave-29 client-px conversion is the scar).
    const ranks = routeRanks(seq, routable.length);
    return {
      ordered,
      km,
      /** `{pid: visit number}` β€” what the route-order COLUMN stores, one integer per record. */
      ranksByPid: routable.reduce((acc, p, i) => {
        const n = ranks[i];
        if (p.pid !== DEPOT_PID && n != null) acc[p.pid] = depotPoint ? n - 1 : n;
        return acc;
      }, {} as Record<number, number>),
      /**
       * The identity of the INPUTS this order was solved from, so staleness can be DERIVED at
       * read time rather than stored. A saved column carries the fingerprint it was solved with;
       * when this one differs, what is on screen would solve to different numbers.
       */
      fingerprint: routeFingerprint(
        routable.map((p) => ({ pid: p.pid, lat: p.lat, lon: p.lon } as RouteStamp)),
        // ⚠ THE RESOLVED ORIGIN, NOT `routeStartPid`. The picker is null while the westernmost
        // default applies, so keying on it would report STALE the moment somebody explicitly
        // selects the stop that was ALREADY the origin β€” the numbers unchanged, the marker on.
        // What the answer depends on is which stop the planner was actually given.
        { roundTrip, startPid: depotPoint ? null : routable[start].pid,
          handOrder: seqEqualsOrder ? null : routeOrder }
      ),
      /** The origin the planner was given, so the saved column records the same one the
       *  fingerprint was taken over. */
      startPid: depotPoint ? null : routable[start].pid,
      links: googleRouteUrls(
        ordered.map((p) => ({ lat: p.lat, lon: p.lon })),
        { roundTrip, coarsePointer, maxStops: mapsPerLink }
      ),
      /** The identity of THIS set of stops in THIS order. The road answer is only about the plan
       *  whose key it carries; anything else on screen makes it stale rather than wrong. */
      key: ordered.map((p) => `${p.pid}@${p.lat.toFixed(6)},${p.lon.toFixed(6)}`).join(",") +
        (roundTrip ? "|rt" : ""),
      depot: depotPoint ? depot : null,
      customerStops: customerRoutable.length,
    };
  }, [routeOn, routable, customerRoutable.length, depotPoint, depot, roundTrip, routeStartPid, routeEndPid,
      coarsePointer, routeOrder, mapsPerLink]);

  /** ⭐ ITEM 7 β€” a MODE change stales the drawn road exactly as a stop change does. Without the
   *  second clause, flipping to Walking would leave driving minutes on screen under a Walking
   *  toggle, which is the failure this whole seam was built to prevent. */
  const roadStale =
    !!road && !!plan && (road.key !== plan.key || road.mode !== travelMode);

  /**
   * W37-T36 β€” ask the routing service for the ROAD answer.
   *
   * β›” CALLED FROM A CLICK AND FROM NOTHING ELSE. There is deliberately no effect that watches
   * `plan` and refetches, because R3 forbids computing a route on a render or a selection change
   * and an effect on `plan` is exactly both. The stale marker is what covers the gap: the user
   * sees that the drawn route no longer matches the stops and asks again when they want to.
   */
  const fetchRoad = useCallback(async () => {
    if (!plan || plan.ordered.length < 2) return;
    const key = plan.key;
    const stops = plan.ordered.map((p) => ({ lat: p.lat, lon: p.lon, pid: p.pid }));
    setRoadBusy(true);
    setRoadErr(null);
    try {
      const res = await routingFetch("/api/v1/geo/route", {
        method: "POST",
        credentials: "same-origin",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stops,
          roundTrip,
          mode: travelMode,
          // The server closes a round trip itself, so there is one authoritative definition of
          // the return leg.  Chosen endpoints remain explicit rather than inferred from an old
          // saved ordering that may have been re-solved locally.
          startPid: routeStartPid ?? undefined,
          endPid: roundTrip ? undefined : routeEndPid ?? undefined,
        }),
      });
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return;
      if (!res.ok) {
        // The SERVER's sentence, not a generic one. It distinguishes a provider timeout, an
        // upstream HTTP failure, an impossible road route and a request that is too large.
        const message = body?.detail?.error?.message || body?.error?.message ||
          body?.detail?.message || body?.detail;
        setRoadErr(String(message ||
          "Driving route unavailable. The straight-line estimate remains on the map; try again."));
        setRoad(null);
        return;
      }
      setRoad({
        km: Number(body.km) || 0,
        minutes: Number(body.minutes) || 0,
        line: Array.isArray(body.line) ? body.line : [],
        key,
        attribution: String(body.attribution || ""),
        // ⚠ THE SERVER'S mode, not the state's. The toggle can move while the request is in
        // flight, and labelling the answer from the state would then caption a driving route
        // "Walking" for exactly as long as nobody re-asked.
        mode: body.mode === "walking" ? "walking" : "driving",
      });
    } catch {
      setRoadErr("The routing service could not be reached. The straight-line estimate remains on the map; try again.");
      setRoad(null);
    } finally {
      setRoadBusy(false);
    }
  }, [plan, roundTrip, routeEndPid, routeStartPid, travelMode, routingFetch]);

  /**
   * β›” THE ONE-SHOT THAT MAKES "PLAN ROUTE" A SINGLE CLICK WITHOUT BECOMING AN AUTO-FETCH.
   *
   * `plan` is null until `routeOn` flips, so the click handler cannot call `fetchRoad` directly:
   * its closure still has the null plan. A ref set by the click and consumed here fires the
   * request exactly once, on the render where the plan first exists.
   *
   * ⚠ This is deliberately NOT `useEffect(..., [plan])` doing the fetch. The effect runs on every
   * plan change; only the ones a CLICK armed do anything. That distinction is R3: a selection
   * change recomputes the plan and must not spend a request.
   */
  useEffect(() => {
    if (!askRoadRef.current || !plan) return;
    askRoadRef.current = false;
    void fetchRoad();
  }, [plan, fetchRoad]);

  // ─────────────────────────────── W38-T20: the order, as a column every colleague reads ───────
  /**
   * The saved route-order columns, refreshed from the server.
   *
   * ⚠ A READ, so it may run without a click, unlike `fetchRoad`. R3 is about not spending a
   * ROUTING request on a render; this asks our own store for a short list of column names and is
   * the only way the STALE marker can exist at all.
   */
  const loadRouteDeliveries = useCallback(async (routeId: string): Promise<RouteDeliveryDto[]> => {
    try {
      const res = await routingFetch(
        `/api/v1/customers/routes/${encodeURIComponent(routeId)}/deliveries`,
        { credentials: "same-origin" },
      );
      const body = res.ok ? await res.json().catch(() => null) : null;
      if (!routingAlive.current) return [];
      return Array.isArray(body?.deliveries) ? body.deliveries : [];
    } catch {
      return [];
    }
  }, [routingFetch]);

  useEffect(() => {
    let current = true;
    setRouteDeliveries(null);
    if (routePanelOpen && activeRouteId) void loadRouteDeliveries(activeRouteId).then((deliveries) => {
      if (current) setRouteDeliveries(deliveries);
    });
    return () => { current = false; };
  }, [activeRouteId, loadRouteDeliveries, routePanelOpen]);

  const copyRouteLinks = useCallback(async () => {
    if (!plan?.links.length) return;
    const text = plan.links.map((link) => link.url).join("\n");
    if (!navigator.clipboard?.writeText) {
      setRouteCopyMsg("Clipboard access is unavailable in this browser.");
      return;
    }
    try {
      await navigator.clipboard.writeText(text);
      setRouteCopyMsg(`${plan.links.length.toLocaleString()} Google Maps link${plan.links.length === 1 ? "" : "s"} copied.`);
    } catch {
      setRouteCopyMsg("The Google Maps links could not be copied.");
    }
  }, [plan]);

  const scheduleNamedRouteDelivery = useCallback(async (
    route: MapRouteDto,
    request: RouteDeliveryRequest,
  ): Promise<string | null> => {
    if (!routingAlive.current) return "This Routing App is no longer open.";
    const result = await requestRouteDelivery(route.id, request, undefined, applicationId);
    if (!routingAlive.current) return "This Routing App is no longer open.";
    if (result.error || !result.delivery) return result.error || "The Route delivery was not saved.";
    setRouteDeliveries((current) => [...(current || []).filter(
      (delivery) => delivery.id !== result.delivery!.id
    ), result.delivery!]);
    return null;
  }, [applicationId]);

  const deleteNamedRouteDelivery = useCallback(async (
    route: MapRouteDto,
    delivery: RouteDeliveryDto,
  ): Promise<string | null> => {
    try {
      const res = await routingFetch(
        `/api/v1/customers/routes/${encodeURIComponent(route.id)}/deliveries/${encodeURIComponent(delivery.id)}`,
        { method: "DELETE", credentials: "same-origin" },
      );
      const body = await res.json().catch(() => null);
      if (!routingAlive.current) return "This Routing App is no longer open.";
      if (!res.ok) return body?.error?.message || body?.detail?.message || "The Route delivery could not be removed.";
      setRouteDeliveries((current) => (current || []).filter((item) => item.id !== delivery.id));
      return null;
    } catch {
      return "The Route delivery could not be removed.";
    }
  }, [routingFetch]);

  /**
   * OWNER INSTRUCTION 8 (W46-T16) - CLICKING A SAVED ROUTE DRAWS ITS PATH AGAIN.
   *
   * The polyline is gated on `plan`, and `plan` is null until `routeOn` is armed over two
   * routable stops. Wave 44 (`cc429a0`, "unify map route and zone navigation") retired the
   * route-order navigator, and the old picker callback - the ONLY writer of `routeOrder` +
   * `routeOn` for a saved route - lost its surface with it. It survived from then only in the
   * compatibility `void [...]` list below, reachable from no click, until W47-T09 deleted it
   * under R9. Since wave 44 every door a person can take to a saved Route (`RouteNav`'s
   * `.cg-w44-route-open` button, and the
   * `aios:route-open` event) sets `activeRouteId` and nothing else, so `plan` stays null and
   * the map draws nothing while erroring nothing. That is the regression, and it predates
   * wave 45 rather than arriving with it.
   *
   * Opening a named Route now arms exactly what the retired picker armed: the stops join
   * `addedPids` (so a stop outside the current View still earns a pin through `mapRows`), the
   * selection is REPLACED by the route's stop order, `routeOrder` takes that order verbatim so
   * `plan.ordered` follows the SAVED sequence rather than the solver's, and the origin picker
   * is cleared. It is one path for both kinds of route: a legacy-compatible projection and a
   * normalized record both reach the client as `visibleStopIds` ordered by `ordered_stops`.
   *
   * NO ROAD REQUEST (R3). This is the local straight-line plan only; the provider is asked when
   * somebody presses Driving route, exactly as the retired picker had it.
   *
   * ONCE PER OPENED ROUTE, VIA A REF KEYED ON THE ROUTE'S OWN STOP SEQUENCE. Keying on the id
   * alone would be spent on the pass where the `aios:route-open` listener has set an id that
   * `namedRoutes` does not carry yet, and would leave `routeOrder` stale after a stop is moved.
   * The sequence key re-arms when the SAVED route changes and never fights a hand reorder made
   * on the map, which does not touch `visibleStopIds`. Closing the detail clears the key so
   * reopening the same route arms it again.
   *
   * A ROUTE WITH FEWER THAN TWO VISIBLE STOPS IS LEFT ALONE rather than armed into the
   * `customerRoutable < 2` teardown effect above.
   */
  const armedRouteRef = useRef<string>("");
  /** ⭐⭐ OWNER 2026-08-31 item 1 - WHICH added pids a ROUTE put there, so a clear can withdraw
   *  exactly those. `addedPids` has two writers: opening a Route arms its stops, and the map's
   *  own "add a record" search adds one by hand. Dropping the whole set on a clear would take
   *  the hand-picked record with it, which is somebody else's work; dropping none is the defect
   *  the owner reported. This ref is the difference between the two. */
  const routeAddedRef = useRef<Set<number>>(new Set());
  useEffect(() => {
    if (!activeNamedRoute) {
      armedRouteRef.current = "";
      return;
    }
    const stops = activeNamedRoute.visibleStopIds;
    if (stops.length < 2) return;
    const signature = `${activeNamedRoute.id}:${stops.join(",")}`;
    if (armedRouteRef.current === signature) return;
    armedRouteRef.current = signature;
    for (const pid of stops) routeAddedRef.current.add(pid);
    setAddedPids((prev) => {
      const next = new Set(prev);
      for (const pid of stops) next.add(pid);
      return next;
    });
    onSelectPids([...stops], "replace");
    setRouteOrder([...stops]);
    setRouteStartPid(null);
    setRouteOn(true);
  }, [activeNamedRoute, onSelectPids]);

  /**
   * ⭐⭐ OWNER 2026-08-31 item 1 β€” AN EMPTIED SELECTION WITHDRAWS WHAT THE ROUTES PUT ON THE MAP.
   *
   * The host's Clear button (`CustomerGrid.tsx`'s selection bar) empties the selection and drops
   * the managed OR clause; the map's half is here, because `addedPids` is MapView's own state and
   * the host has no handle on it. Without this, the grid loses the rows and the map keeps the
   * pins β€” half a fix, and the half a person is looking at while they press the button.
   *
   * ⚠ ONLY ROUTE-ORIGIN PIDS, and only when the selection is EMPTY. A record added by hand from
   * the map's own search stays; a Route still ticked always holds a selection, so this cannot
   * fire underneath one.
   */
  useEffect(() => {
    if (selectedPids.size > 0 || routeAddedRef.current.size === 0) return;
    const withdraw = routeAddedRef.current;
    routeAddedRef.current = new Set();
    armedRouteRef.current = "";
    setSelectedRouteIds((current) => (current.size ? new Set<string>() : current));
    setAddedPids((prev) => {
      if (![...withdraw].some((pid) => prev.has(pid))) return prev;
      const next = new Set(prev);
      for (const pid of withdraw) next.delete(pid);
      return next;
    });
  }, [selectedPids]);

  /**
   * ⭐⭐ W47-T07 (owner instruction 9) β€” EVERY TICKED ROUTE ON THE MAP AT ONCE, EACH IN ITS OWN
   * COLOUR. Owner: *"we also need a checkbox for us to be able to see each route all together on
   * the map. That means we need the ability to color each routes too so its easy to see on the
   * map."*
   *
   * β›” THIS IS A GENERALISATION, NOT A SECOND ROUTE SYSTEM. `plan` draws ONE route - the opened
   * one - with its solved order and its road answer, and it keeps doing exactly that. These are
   * the OTHER ticked routes, drawn from the stop order the record already carries
   * (`visibleStopIds`), so nothing here asks the planner or the road provider for anything.
   *
   * ⭐ THE COLOUR IS THE RECORD'S OWN, AND IT ALREADY PERSISTS: `route_system.py::_color` stamps
   * every new Route with a distinct default from `_ROUTE_COLORS` by ordinal, and the sidebar
   * swatch has always read `route.color`. So the line and the swatch cannot disagree - they are
   * one value - which is the half of this ticket a screenshot has to show.
   *
   * β›” IT GOES THROUGH `zonePaint`. A Route whose colour arrived empty would otherwise paint the
   * SVG initial `fill`/`stroke`, which is BLACK - the exact defect W47-T02 closed for Zones, and
   * a new render site is a new chance to reopen it.
   *
   * ⚠ A STOP THAT IS NOT ON THE MAP IS DROPPED, NOT FAKED. `points` carries only rows that
   * actually plot, so a route whose stops sit outside the current filter draws the part it can
   * and is skipped entirely below two points. That is a true picture of a partial route rather
   * than a line to nowhere.
   */
  const overlaidRoutes = useMemo(() => {
    if (!view || selectedRouteIds.size === 0) return [];
    const byPid = new Map(points.map((point) => [point.pid, point.p]));
    return namedRoutes
      .filter((route) => selectedRouteIds.has(route.id))
      .map((route) => ({
        id: route.id,
        color: zonePaint(route.color),
        pts: (route.visibleStopIds || [])
          .map((pid) => byPid.get(pid))
          .filter((at): at is { x: number; y: number } => !!at),
      }))
      .filter((overlay) => overlay.pts.length > 1);
  }, [namedRoutes, points, selectedRouteIds, view]);

  /** The drawn road, projected once per answer. Straight-line fallback stays in `plan`, so a map
   *  that never got a road answer still shows the sequence it worked out for itself. */
  const roadPath = useMemo(() => {
    if (!road || road.line.length < 2) return null;
    return road.line
      .map((c) => {
        const p = project(c[0], c[1]);
        return `${p.x.toFixed(2)},${p.y.toFixed(2)}`;
      })
      .join(" ");
  }, [road]);

  /**
   * W37-T37 β€” SELECTED RECORDS THAT COULD GAIN A LOCATION.
   *
   * β›” SELECTED, and that word is the whole guard. There is no expression here that means "every
   * record without a pin": R3 forbids geocoding a table, and the way to forbid it is to have no
   * code that can express it. Somebody chose these rows on this screen.
   */
  const geocodable = useMemo(() => {
    const addrKey = coordField?.geocode?.addressField;
    if (!addrKey || !coordField || selectedPids.size === 0) return [];
    const placed = new Set(points.map((p) => p.pid));
    return mapRows.filter((r) => selectedPids.has(r.pid) && !placed.has(r.pid));
  }, [mapRows, coordField, selectedPids, points]);

  /** The estimate, in the words a person plans with. ⚠ Built from the SERVER's measured
   *  seconds-per-address, never from the published rate limit: the limit is a floor on politeness
   *  and was measured at a third of the real latency, so quoting it promises a minute and takes
   *  three. */
  const geoEstimate = useMemo(() => {
    const secs = Math.round(geocodable.length * geoSeconds);
    if (secs < 90) return `about ${Math.max(5, secs)} seconds`;
    const mins = Math.round(secs / 60);
    return `about ${mins} minute${mins === 1 ? "" : "s"}`;
  }, [geocodable.length, geoSeconds]);

  const runGeocode = useCallback(async () => {
    const addrKey = coordField?.geocode?.addressField;
    if (!addrKey || (!onGeocoded && !geocodeSessionOnly) || geocodable.length === 0) return;
    setGeo({ busy: true, done: 0, total: geocodable.length, found: 0, error: null });
    let found = 0;
    try {
      // β›” BATCHED BY THE SERVER'S OWN `maxBatch`, and the loop lives HERE rather than there on
      // purpose: a single request that sat on the connection for eight minutes would be killed by
      // every proxy between us, and would report nothing until it finished. Small calls mean the
      // count on screen moves, and an interrupted run keeps the records it already placed.
      for (let i = 0; i < geocodable.length; i += geoBatch) {
        const slice = geocodable.slice(i, i + geoBatch);
        const res = await fetch("/api/v1/geo/geocode", {
          method: "POST",
          credentials: "same-origin",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            records: slice.map((r) => ({ key: r.pid, row: r })),
            config: { addressField: addrKey, country: coordField?.geocode?.country },
          }),
        });
        const body = await res.json().catch(() => null);
        if (!routingAlive.current) return;
        if (!res.ok) {
          setGeo((g) => ({
            ...g, busy: false,
            error: (body && body.detail && body.detail.error && body.detail.error.message) ||
              "The address lookup service did not answer.",
          }));
          return;
        }
        const located = (body.results || [])
          .filter((r: { found?: boolean }) => r && r.found)
          .map((r: { key: number; lat: number; lon: number }) => ({
            pid: Number(r.key), lat: r.lat, lon: r.lon,
          }));
        const writes = located.map((r: { pid: number; lat: number; lon: number }) => ({
          pid: r.pid,
          // The cell shape contract C7 fixes, at the precision `googleMapsUrl` already uses so
          // the cell, the pin and the hand-off link agree to the digit.
          value: `${r.lat.toFixed(6)},${r.lon.toFixed(6)}`,
        }));
        found += located.length;
        // ⭐ HANDED OVER PER BATCH, not at the end. A run over 300 records is minutes long, and
        // a person who navigates away mid-run should keep every coordinate already paid for.
        if (located.length && geocodeSessionOnly) {
          setSessionCoordinates((current) => {
            const next = new Map(current);
            for (const point of located) next.set(point.pid, { lat: point.lat, lon: point.lon });
            return next;
          });
        } else if (writes.length) {
          onGeocoded?.(writes);
        }
        setGeo((g) => ({ ...g, done: Math.min(g.total, i + slice.length), found }));
      }
      setGeo((g) => ({ ...g, busy: false }));
    } catch {
      setGeo((g) => ({ ...g, busy: false, error: "The address lookup could not be reached." }));
    }
  }, [coordField, onGeocoded, geocodable, geoBatch, geocodeSessionOnly]);

  /** The depot has no row, so it uses the address-list form of the same bounded lookup and wait. */

  /**
   * ⭐ OWNER ITEM 9 β€” TAKE THIS CUSTOMER OFF THE ROUTE.
   *
   * β›” IT DESELECTS RATHER THAN KEEPING A LOCAL EXCLUSION LIST, and that is the whole reason the
   * panel stays coherent: the head counts `selectedPids`, the stop list counts `plan.ordered`,
   * and an exclusion set would have made those two disagree the moment anybody used this. The
   * hand-picked order drops it too, or a removed stop would be re-appended by `plan`'s "anything
   * newly selected joins in the planner's order" clause the next time the selection moved.
   */
  const removeStop = useCallback(
    (pid: number) => {
      if (pid === DEPOT_PID) return;
      onSelectPids([...selectedPids].filter((x) => x !== pid), "replace");
      setRouteOrder((prev) => (prev ? prev.filter((x) => x !== pid) : prev));
      setAddedPids((prev) => {
        if (!prev.has(pid)) return prev;
        const next = new Set(prev);
        next.delete(pid);
        return next;
      });
    },
    [onSelectPids, selectedPids]
  );

  /**
   * ⭐ OWNER ITEM 9 β€” ADD A RECORD THE VIEW IS NOT SHOWING.
   *
   * It joins `addedPids` (so `mapRows` gains it and it earns a pin) AND the selection (so every
   * count in this panel keeps meaning the same thing). Appended to a hand-picked order rather
   * than inserted, because the person adding it is the one who knows where in the day it goes.
   */
  const addRecord = useCallback(
    (pid: number) => {
      setAddedPids((prev) => (prev.has(pid) ? prev : new Set(prev).add(pid)));
      onSelectPids([pid], "add");
      setRouteOrder((prev) => (prev && !prev.includes(pid) ? [...prev, pid] : prev));
    },
    [onSelectPids]
  );

  /**
   * ⭐ OWNER ITEM 9 β€” WHAT THE "Add a record" SEARCH MAY OFFER.
   *
   * β›” THE WHOLE BOOK MINUS WHAT IS ALREADY ON THE ROUTE, and "the whole book" is `allRows` (see
   * the prop's own note): after the row wall, before the view's filter. Records already selected
   * are excluded because offering them would let a person "add" a stop and see nothing change.
   * ⚠ NOT FILTERED BY WHETHER A RECORD HAS A LOCATION. One that has none is addable and then
   * lands in the "No location, so not routed" chip, which is the disclosure that already exists;
   * hiding it here would make a customer the user can name simply absent from the search, with no
   * sentence anywhere saying why.
   */
  /**
   * β›”β›” OWNER, 2026-08-23 β€” NAMED RECORDS FIRST, UNNAMED LAST, AND THAT IS WHY THE LIST
   * LOOKED EMPTY OF ANYTHING USEFUL UNTIL YOU TYPED.
   *
   * Owner: *"when I click the 'search the database' under the routes, the dropdown shows ??? for
   * populating the route. Only when I search and type something does it show something."*
   *
   * This built EVERY title as `name || "#" + pid` and then sorted the whole mixed list with
   * `localeCompare`, which files punctuation ahead of letters. `PICKER_LIST_CAP` then takes the
   * first 40 β€” so with an unsearched query the panel showed forty rows of `#12345` and not one
   * customer name, and typing anything at all filtered those placeholder titles away and revealed
   * the real records underneath. The bug was never the search; it was the ORDER the cap sliced.
   *
   * ⚠ THE UNNAMED ARE NOT DROPPED, THEY ARE MOVED. A record with no value in the identity column
   * is still addable β€” it may be exactly the stop somebody is looking for β€” and hiding it would
   * make a record the user can see in the grid simply absent from the search with nothing saying
   * why. It sorts last and says what it is instead of wearing a bare id.
   */
  const addableRecords = useMemo(() => {
    if (!allRows || allRows.length === 0) return [];
    const named: { pid: number; title: string; sort: string }[] = [];
    const rest: { pid: number; title: string }[] = [];
    for (const r of allRows) {
      if (selectedPids.has(r.pid)) continue;
      const raw = String(r[field.key] ?? "").trim();
      // β›” THE FIRST LETTER OR DIGIT ONWARD IS WHAT A PERSON ALPHABETISES BY. Leading
      // punctuation is not part of a name, so `'AMBIANCE` and `AMBIANCE` file together instead
      // of the apostrophe deciding.
      const sort = raw.replace(/^[^\p{L}\p{N}]+/u, "");
      if (sort) named.push({ pid: r.pid, title: raw, sort });
      // β€” no letter and no digit anywhere: `?`, `-`, `--`. Not a name; it is a record whose
      // name was never filled in, wearing a placeholder somebody typed.
      else if (raw) rest.push({ pid: r.pid, title: `${raw} (record ${r.pid})` });
      else rest.push({ pid: r.pid, title: `Unnamed record ${r.pid}` });
    }
    named.sort((a, b) => a.sort.localeCompare(b.sort));
    rest.sort((a, b) => a.pid - b.pid);
    return [...named.map(({ pid, title }) => ({ pid, title })), ...rest];
  }, [allRows, selectedPids, field.key]);

  const moveStop = useCallback(
    (pid: number, delta: number) => {
      if (!plan || pid === DEPOT_PID) return;
      const ids = plan.ordered.filter((p) => p.pid !== DEPOT_PID).map((p) => p.pid);
      const at = ids.indexOf(pid);
      const to = at + delta;
      if (at < 0 || to < 0 || to >= ids.length) return;
      const next = [...ids];
      next.splice(to, 0, next.splice(at, 1)[0]);
      setRouteOrder(next);
    },
    [plan]
  );

  // ⭐ "Keep these compatibility hooks live UNTIL ROUTE-ORDER COLUMNS ARE RETIRED SERVER-SIDE"
  // is what this list used to say. They are retired: every tenant schema holds zero of them and
  // the four doors are deleted. So the entries that existed only to serve a legacy COLUMN went
  // with it -- `routeCols`, the `routeEdit*` bag, `updateRouteDetails` and the listing fetch that
  // put a 404 in the console on every panel open. What remains below is the retired-PANEL surface
  // (W47-T09 / R9), which is a different retirement and still parks its state here unread.
  void [
    formatDuration, ROUTE_STOP_CAP, RecordPicker, setDepot, setTravelMode, travelModes,
    roadBusy, roadErr, routeCopyMsg,
    openErr, naming, nameDraft, setNameDraft,
    saveBusy, saveMsg, saveErr, unroutable, unroutableNames,
    copyRouteLinks,
    removeStop, addRecord, addableRecords, moveStop,
    // β›” R14 (W50-T14, 2026-09-03) β€” `requestRoutePinMembership` PARKS HERE, IT IS NOT DELETED.
    // R14 retired the pin CLICK and the pin ENTER entries to it, which were its only two callers,
    // so without this line `noUnusedLocals` refuses the file. The machinery itself stays whole and
    // asserted (`verify_map.py`'s `no-arbitrary-route`, `actual-membership`, `single-stop-door`
    // and `visible-confirmation` legs all still hold): what R14 removed is one DOOR, not the room.
    // ⚠ `confirmRoutePinMembership` and the confirm dialog are still wired to each other and are
    // deliberately left that way; they are simply unreachable until something sets a prompt again.
    requestRoutePinMembership,
    // W47-T09 / R9 deleted the always-false staleness derivation and, with it, the two retired
    // callbacks that were its only real writers. These are what those two left behind: state the
    // panel still allocates, plus the host callback that revealed a freshly saved route column.
    // β›” NONE OF IT IS A NEW RETIREMENT. Each name was already reachable from no click; listing
    // it here keeps the state and the prop in place, unread, for whoever puts the panel back.
    onRouteFieldCreated, saveTarget, setOpenedRoute, setOpenErr, nextLabel, setNaming,
    setSaveBusy, setSaveMsg, setSaveErr,
  ];

  const paint = useCallback(
    (p: MapPoint) => {
      const k = p.colorKey ?? "";
      const category = !colorBuckets ? DEFAULT_PIN
        : k === "" ? OVERFLOW : colorBuckets.swatch.get(k) ?? OVERFLOW;
      // R23: the bound size measure's sign overrides its category colour.
      if (sizeField && typeof p.size === "number" && Number.isFinite(p.size) && p.size < 0) return NEGATIVE_PIN;
      return category;
    },
    [colorBuckets, sizeField]
  );

  const radius = useCallback(
    (p: MapPoint) => {
      // `sizeRange` is null without a size pick, so one helper decides every bubble's radius.
      return pointRadius(p.size, sizeRange, R_PLAIN, R_MIN, R_MAX, R_NULL);
    },
    [sizeRange]
  );

  /**
   * Client coords -> the svg's own user-space coords.
   *
   * ⚠ The maths lives in `clientToUser` (mapProjection) rather than here, and
   * that placement is the fix's other half. Wave 8 wrote the conversion inline
   * in this .tsx β€” where the gate's negative controls, every one of which
   * mutates the compiled `mapProjection.js`, could not reach it. So the box-
   * select legs passed on coordinates handed to them ALREADY in user space, and
   * a broken conversion shipped green for four waves. See `clientToUser`.
   */
  const localPoint = useCallback(
    (clientX: number, clientY: number): Pt => {
      if (!svgEl) return { x: 0, y: 0 };
      return clientToUser(clientX, clientY, svgEl.getBoundingClientRect(), VIEW_W, VIEW_H);
    },
    [svgEl]
  );

  /**
   * ⚠ Wheel zoom MUST be a native, non-passive listener. React registers
   * `wheel` PASSIVELY at the root, so `e.preventDefault()` inside an `onWheel`
   * prop is a silent no-op: the page scrolls out from under the map while you
   * zoom, which reads as "the zoom is broken". Nothing in a screenshot shows
   * this, and no assertion on the rendered DOM can see it either.
   *
   * The zoom maths itself is `zoomAt` β€” the function the gate already proves
   * holds the point under the cursor still. Wave 8 re-derived that formula
   * inline here, so the tested copy and the shipped copy were two copies.
   */
  useEffect(() => {
    if (!svgEl) return;
    const onWheelNative = (e: WheelEvent) => {
      e.preventDefault();
      const { x, y } = localPoint(e.clientX, e.clientY);
      touchedRef.current = true;
      setView((v) => (v ? zoomAt(v, Math.exp(-e.deltaY * 0.0016), x, y, kMin, kMax) : v));
    };
    svgEl.addEventListener("wheel", onWheelNative, { passive: false });
    return () => svgEl.removeEventListener("wheel", onWheelNative);
  }, [svgEl, localPoint, kMin, kMax]);

  /** Zoom about the viewport centre β€” the button and keyboard gesture, where
   *  there is no cursor to hold still. */
  const zoomBy = useCallback(
    (factor: number) => {
      touchedRef.current = true;
      setView((v) => (v ? zoomAt(v, factor, VIEW_W / 2, VIEW_H / 2, kMin, kMax) : v));
    },
    [kMin, kMax]
  );

  /**
   * ⭐⭐ OWNER ITEM 1 (2026-08-23) β€” TURN THE MAP, 5 DEGREES A CLICK.
   *
   * Owner: *"we need to add two more button for that navigation. Rotate left and Rotate right.
   * Where every click is say rotating the map by 5 degrees."*
   *
   * β›” `touchedRef` IS SET, AND WITHOUT IT THE BEARING WOULD NOT SURVIVE THE NEXT EDIT. The
   * seeding effect above re-fits whenever `fit` changes UNLESS the user has touched the camera,
   * and `fit` changes on every points change β€” a cell edit, a filter, an arriving row. Rotating
   * without panning would then look like the map springing back to north on its own.
   *
   * ⚠ ABOUT THE VIEWPORT CENTRE, which is what a compass control means by "turn". `rotateAt`
   * is `zoomAt`'s sibling and holds that point still, so the geography under the middle of the
   * frame is the geography you were looking at.
   */
  const rotateBy = useCallback((deg: number) => {
    touchedRef.current = true;
    setView((v) => (v ? rotateAt(v, deg, VIEW_W / 2, VIEW_H / 2) : v));
  }, []);

  /**
   * β›” AND FIT PUTS NORTH BACK UP. `fit` is a fresh `{k, tx, ty}` with no `rot`, so replacing
   * the view with it resets the bearing by construction rather than by a line that could be
   * forgotten. It is deliberate rather than incidental: a compass with no way back to north is a
   * control with no undo, and `fitView` would otherwise have to frame the bounding box of the
   * ROTATED points to keep every pin on screen. "Fit to data" is the reset, and the button's
   * title says so.
   */
  const doFit = useCallback(() => {
    touchedRef.current = false;
    setView(fit);
  }, [fit]);

  const panBy = useCallback((dx: number, dy: number) => {
    touchedRef.current = true;
    setView((v) => (v ? { ...v, tx: v.tx + dx, ty: v.ty + dy } : v));
  }, []);

  /**
   * β›”β›” W46-T28 β€” THE ONE PLACE A CLICK-DRAWN OUTLINE BECOMES A SAVEABLE BOUNDARY, and the
   * reason the owner could not save. Before this, that conversion lived ONLY in the `Enter`
   * branch of `onFrameKeyDown`, which fires only while `.cg-map-frame` itself holds focus. The
   * shape a user draws by clicking is drawn on the map and then NAMED in the panel, so by the
   * time they are done the focus is in a text input and `Enter` never reaches the map. The
   * panel's only draft control was "Stop drawing", which DISCARDS the points. So the outline
   * never reached `drawnZoneGeometry`, the Save button stayed `disabled`, and a disabled button
   * cannot explain itself: the refusal was real and completely silent.
   *
   * ⚠ It returns the geometry as well as storing it, because a caller in the same tick cannot
   * read the state it just set. `null` means it refused, and it has already said why in
   * `zoneErr` β€” a caller must not then report a second, vaguer reason over the top.
   */
  const finishZoneDraft = useCallback((): ZoneGeometry | null => {
    const draft = zoneKeyboardDraft;
    if (!draft || !view) return null;
    let geometry: ZoneGeometry;
    if (draft.shape === "polygon") {
      if (draft.points.length < 3) {
        setZoneErr("Add at least three vertices, then finish the shape.");
        return null;
      }
      const coordinates = draft.points
        .map((screen) => unproject(fromScreen(screen, view)))
        .map(({ lon, lat }) => [lon, lat]);
      geometry = { type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] };
    } else {
      if (!draft.center) {
        setZoneErr("Place the circle center first, then its edge.");
        return null;
      }
      // β›” W46-T28 β€” A CIRCLE WITH NO EDGE CLICK IS A ONE METRE ZONE. `cursor` still sits on
      // `center` until the second click, and `Math.max(1, 0)` below would happily mint a Zone
      // too small to see and holding no records: instruction 16's own complaint, saved. The
      // panel button puts that one click away, so the refusal is stated rather than shipped.
      if (draft.center.x === draft.cursor.x && draft.center.y === draft.cursor.y) {
        setZoneErr("Click the circle edge to give the Zone a size, then finish the shape.");
        return null;
      }
      const center = unproject(fromScreen(draft.center, view));
      const edge = unproject(fromScreen(draft.cursor, view));
      geometry = {
        type: "Circle",
        center: [center.lon, center.lat],
        radiusMeters: Math.max(1, Math.round(haversineKm(
          { lat: center.lat, lon: center.lon }, { lat: edge.lat, lon: edge.lon }
        ) * 1000)),
      };
    }
    setDrawnZoneGeometry(geometry);
    setZoneKeyboardDraft(null);
    setZoneErr(null);
    return geometry;
  }, [zoneKeyboardDraft, view]);

  /** The camera had NO keyboard path at all before wave 9 β€” scroll wheel only,
   *  which is unusable without a mouse and unreachable for anyone driving the
   *  page from the keyboard. */
  const onFrameKeyDown = useCallback(
    (e: ReactKeyboardEvent<HTMLDivElement>) => {
      if (zoneKeyboardDraft) {
        const keyboardStep = e.shiftKey ? 24 : 8;
        const moved = { ...zoneKeyboardDraft.cursor };
        if (e.key === "ArrowLeft") moved.x = Math.max(8, moved.x - keyboardStep);
        else if (e.key === "ArrowRight") moved.x = Math.min(VIEW_W - 8, moved.x + keyboardStep);
        else if (e.key === "ArrowUp") moved.y = Math.max(8, moved.y - keyboardStep);
        else if (e.key === "ArrowDown") moved.y = Math.min(VIEW_H - 8, moved.y + keyboardStep);
        else if (e.key === " ") {
          if (zoneKeyboardDraft.shape === "polygon")
            setZoneKeyboardDraft({ ...zoneKeyboardDraft, points: [...zoneKeyboardDraft.points, zoneKeyboardDraft.cursor] });
          else if (!zoneKeyboardDraft.center)
            setZoneKeyboardDraft({ ...zoneKeyboardDraft, center: zoneKeyboardDraft.cursor });
          setZoneErr(null);
          e.preventDefault();
          return;
        } else if (e.key === "Enter") {
          if (!view) return;
          // W46-T28 β€” the same commit the panel's "Finish shape" button calls. Two controls,
          // one conversion: a second copy is how the two endings drift apart.
          finishZoneDraft();
          e.preventDefault();
          return;
        } else if (e.key === "Escape") {
          setZoneKeyboardDraft(null);
          setZoneErr(null);
          e.preventDefault();
          return;
        } else return;
        setZoneKeyboardDraft({ ...zoneKeyboardDraft, cursor: moved });
        e.preventDefault();
        return;
      }
      const step = e.shiftKey ? 160 : 60;
      switch (e.key) {
        case "ArrowLeft": panBy(step, 0); break;
        case "ArrowRight": panBy(-step, 0); break;
        case "ArrowUp": panBy(0, step); break;
        case "ArrowDown": panBy(0, -step); break;
        case "+": case "=": zoomBy(1.6); break;
        case "-": case "_": zoomBy(1 / 1.6); break;
        // ⭐ ITEM 1 β€” the bracket keys turn the map, the same 5 degrees the buttons do. Not the
        // arrows: those are the pan, and shift-arrow is already the bigger pan step.
        case "[": rotateBy(-ROTATE_STEP); break;
        case "]": rotateBy(ROTATE_STEP); break;
        case "0": doFit(); break;
        // Esc abandons a marquee mid-drag. It falls THROUGH when there is no
        // drag, so it keeps closing whatever the host has open.
        case "Escape": if (!drag) return; setDrag(null); break;
        default: return;
      }
      e.preventDefault();
    },
    [panBy, zoomBy, rotateBy, doFit, drag, view, zoneKeyboardDraft, finishZoneDraft]
  );

  const startKeyboardZoneDrawing = useCallback(() => {
    setZoneKeyboardDraft({
      shape: zoneDrawShape,
      cursor: { x: VIEW_W / 2, y: VIEW_H / 2 },
      points: [],
    });
    setZoneErr(null);
    requestAnimationFrame(() => mapFrameRef.current?.focus());
  }, [zoneDrawShape]);

  /** W46-T17 β€” A CLICK ON THE MAP IS THE PRIMARY WAY TO DRAW A ZONE. The arrow
   *  keys and Space in `onFrameKeyDown` still work and are still the only path
   *  for someone with no pointer, so that handler stays; what changed is that
   *  nobody has to be TOLD about it to draw a shape. The cursor moves to the
   *  click as well as the point being kept, so the rubber band that follows the
   *  pointer starts from where the user just clicked. */
  const addZoneDraftVertex = useCallback((at: Pt) => {
    setZoneKeyboardDraft((draft) => {
      if (!draft) return draft;
      if (draft.shape === "polygon")
        return { ...draft, cursor: at, points: [...draft.points, at] };
      if (!draft.center) return { ...draft, cursor: at, center: at };
      return { ...draft, cursor: at };
    });
    setZoneErr(null);
  }, []);

  const onPointerDown = useCallback(
    (e: ReactPointerEvent<SVGSVGElement>) => {
      if (e.button !== 0 || !view) return;
      const { x, y } = localPoint(e.clientX, e.clientY);
      movedRef.current = false;
      // β›”β›” THE CAPTURE IS TAKEN LAZILY, IN `onPointerMove`, AND MOVING IT THERE IS THE WHOLE
      // FIX FOR W38-T09 (found by wave-38 QA on the deployed build). This line used to read
      // `e.currentTarget.setPointerCapture(e.pointerId)`, unconditionally, on every pointerdown
      // anywhere in the SVG -- including on a pin. Pointer capture retargets the REST of the
      // gesture to the capture element, so `pointerup`, `mouseup` and the synthesised `click`
      // all landed on the `<svg>` and a pin's own `onClick` NEVER RAN. Measured live:
      //     pointerdown -> cg-map-pin      mousedown -> cg-map-pin
      //     pointerup   -> cg-map-svg      mouseup   -> cg-map-svg      click -> cg-map-svg
      // ⚠ RELEASING ON `pointerup` DOES NOT SAVE IT, and that was the tempting wrong fix: the
      // release below already ran and the click was still retargeted. Reproduced in a 20-line
      // isolation page with zero app code, IDENTICALLY in headed and headless Chromium, so it is
      // browser behaviour rather than a test-harness artifact.
      // ⭐ THE PIN'S HANDLER WAS ALWAYS CORRECT. `onOpen`, `pinSelect`, the drawer and the cohort
      // path were all provably healthy (keyboard Enter opened the record; shift-drag, which the
      // SVG handles itself and so is immune to the retargeting, selected 2,381 pins). Only
      // pointer DELIVERY to a pin was broken -- and it had been since wave 8, thirty waves before
      // the ticket that wired this handler. `git log -S "setPointerCapture"` returns one commit.
      downRef.current = { id: e.pointerId, cx: e.clientX, cy: e.clientY };
      // Shift (or Ctrl/Cmd) turns the drag into a SELECTION rectangle; a plain
      // drag pans. Both gestures are on the same button because a map that
      // needs a mode toggle to select is a map people never select on.
      if (e.shiftKey || e.ctrlKey || e.metaKey)
        setDrag(lassoTool ? { kind: "lasso", pts: [{ x, y }] } : { kind: "rect", x0: x, y0: y, x1: x, y1: y });
      else panRef.current = { x, y, tx: view.tx, ty: view.ty };
    },
    [view, localPoint, lassoTool]
  );

  const onPointerMove = useCallback(
    (e: ReactPointerEvent<SVGSVGElement>) => {
      const { x, y } = localPoint(e.clientX, e.clientY);
      // ⭐ W46-T17 β€” the in-progress outline TRACKS THE POINTER while drawing is
      // armed. Without this the first click leaves `points` and `cursor` on the
      // same coordinate, so the polyline has zero length and the shape reads as
      // invisible all over again. A pan or a marquee owns the pointer instead.
      if (zoneKeyboardDraft && !drag && !zoneMove && !zoneVertex && !panRef.current)
        setZoneKeyboardDraft((draft) =>
          draft && (draft.cursor.x !== x || draft.cursor.y !== y)
            ? { ...draft, cursor: { x, y } }
            : draft);
      // ⭐ W46-T28 β€” ONE VERTEX FOLLOWS THE POINTER. It sits above the whole-boundary branch
      // because a handle is a smaller, more specific target sitting ON the boundary: without
      // this order, grabbing a corner would translate the entire Zone instead of reshaping it.
      // ⚠ Every move recomputes from `zoneVertex.geometry`, the shape as it was when the drag
      // STARTED, so the answer is a function of where the pointer is now and not of how it got
      // there. There is no travel threshold here on purpose: a corner nudged two pixels is a
      // deliberate adjustment, where the same two pixels on a whole boundary is a mis-click.
      if (zoneVertex && view) {
        movedRef.current = true;
        const at = unproject(fromScreen({ x, y }, view));
        setZoneGeometryDraft({
          id: zoneVertex.zone.id,
          geometry: moveZoneVertex(zoneVertex.geometry, zoneVertex, { lon: at.lon, lat: at.lat }),
        });
        return;
      }
      if (zoneMove && view) {
        if (Math.abs(x - zoneMove.start.x) + Math.abs(y - zoneMove.start.y) <= 2) return;
        movedRef.current = true;
        const origin = unproject(fromScreen(zoneMove.start, view));
        const current = unproject(fromScreen({ x, y }, view));
        setZoneGeometryDraft({
          id: zoneMove.zone.id,
          geometry: translateZoneGeometry(zoneMove.geometry, {
            lon: current.lon - origin.lon,
            lat: current.lat - origin.lat,
          }),
        });
        return;
      }
      // ⭐⭐ THE LAZY CAPTURE (W38-T09's fix). A gesture only becomes a drag once it has TRAVELLED,
      // so the capture is taken here rather than on pointerdown. A zero-movement click therefore
      // never captures and reaches the pin it was aimed at; a pan or a marquee captures the
      // instant it stops being a click, which is what keeps the pointer inside this handler when
      // the cursor leaves the SVG mid-drag. Both directions proven in isolation before this
      // landed: a plain click fires the pin's own `onClick`, and a real drag still logs the
      // capture and retargets exactly as it did before.
      // ⚠ THE THRESHOLD IS IN CLIENT PIXELS, deliberately unlike the two below it. Those compare
      // LOCAL (viewBox) coordinates to decide whether a gesture counts as travel for selection;
      // this one asks whether the BROWSER should stop delivering events to what is under the
      // cursor, which is a screen-space question at every zoom.
      const dn = downRef.current;
      if (dn && dn.id === e.pointerId && !e.currentTarget.hasPointerCapture(e.pointerId)
          && Math.abs(e.clientX - dn.cx) + Math.abs(e.clientY - dn.cy) > 3)
        e.currentTarget.setPointerCapture(e.pointerId);
      if (drag) {
        // ⚠ W37-T30: this used to set `movedRef` UNCONDITIONALLY, and that is what swallowed a
        // shift-CLICK. Holding shift starts a marquee on pointerdown, so a shift-click is a
        // marquee that never travels; one stray pointermove then marked the gesture "moved" and
        // the pin's onClick returned early. Measured on the render probe: the click fired, the
        // handler ran, and the selection did not change.
        // The threshold is the pan branch's own rule, applied to the same question, and a marquee
        // that really was drawn clears it long before `drawn` (> 3 px) lets it select anything.
        const from = drag.kind === "rect" ? { x: drag.x0, y: drag.y0 } : drag.pts[0];
        if (Math.abs(x - from.x) + Math.abs(y - from.y) > 2) movedRef.current = true;
        setDrag((d) => {
          if (!d) return d;
          if (d.kind === "rect") return { ...d, x1: x, y1: y };
          // `pointermove` fires far faster than a loop needs vertices, so a slow
          // hand tracing 200 px would otherwise build a thousand-point polygon
          // that every pin is then tested against on every frame. Drop a sample
          // that has not travelled ~2 px β€” the viewBox is fixed relative to the
          // screen, so this threshold means the same thing at every zoom.
          const last = d.pts[d.pts.length - 1];
          if (Math.abs(x - last.x) + Math.abs(y - last.y) < 2) return d;
          return { kind: "lasso", pts: [...d.pts, { x, y }] };
        });
        return;
      }
      const pan = panRef.current;
      if (!pan) return;
      if (Math.abs(x - pan.x) + Math.abs(y - pan.y) > 2) movedRef.current = true;
      touchedRef.current = true;
      setView((v) => (v ? { ...v, tx: pan.tx + (x - pan.x), ty: pan.ty + (y - pan.y) } : v));
    },
    [drag, localPoint, zoneMove, zoneVertex, view, zoneKeyboardDraft]
  );

  /**
   * Table's opt-in selects on click and opens on double-click. The default surface keeps R10.
   *
   * β›”β›” W38-T09 (ruling R10) β€” A SINGLE CLICK ON A PIN OPENS THE RECORD. This SUPERSEDES the
   * single-click-SELECTS half of W37-T30 (D-135), which was built deliberately one wave ago. The
   * paragraph W37-T30 wrote is kept below rather than deleted, because its argument is still the
   * argument that has to be traded against, and a reader who only sees the winner cannot tell a
   * decision from an accident.
   *
   * ⭐ WHAT W37-T30 ARGUED, AND IT WAS NOT WRONG AT THE TIME. Owner item 19 moved the whole
   * product off click-to-open: in the grid "the single click that used to open a record now
   * highlights it", and opening moved to a deliberate affordance (CustomerGrid.tsx, the
   * hover-only Expand). The map went on firing `onOpen` on a bare click, so the one view built
   * around choosing a SET of records was the one view where choosing was impossible, and the
   * "N selected" bar, "Add to cohort" and the route planner all sat behind a gesture the map did
   * not have.
   *
   * ⭐ WHAT R10 TRADES IT FOR. A pin is not a row. A row lives in a sheet where the cursor already
   * means "this cell", so click-to-highlight costs a user nothing; a pin is a target you had to
   * AIM at, and the thing you wanted after aiming is the record. Every set-building gesture the
   * map grew for item 19 SURVIVES, and not one of them is the plain click: shift-drag and the
   * lasso build a cohort, shift-alt-drag extends one, a modifier click toggles a single pin in or
   * out, and the keyboard keeps Space for select and Enter for open.
   *
   * ⚠ SO `pinSelect`'s NON-ADDITIVE BRANCH IS NOW KEYBOARD-ONLY, not dead. A plain Space still
   * replaces the selection with the focused pin; a pointer no longer has that gesture at all.
   * Deleting the branch as unreachable would take the keyboard's only "just this one" with it.
   *
   * β›” AND `movedRef` IS NOW LOAD-BEARING FOR A WORSE REASON THAN THE ONE IT WAS WRITTEN FOR.
   * Before R10, a pan or a box-drag that happened to finish on top of a pin mis-SELECTED it.
   * After R10 the same stray gesture would OPEN a drawer over the map. Whoever next reads that
   * early return as noise should read this sentence instead: its failure mode got louder.
   *
   * Toggle rather than plain accumulate is done here rather than asked for from the host, because
   * `onSelectPids` offers "replace" and "add" only, and a second shift-click that cannot undo the
   * first is a trap on a map where pins overlap.
   */
  const pinSelect = useCallback(
    (pid: number, additive: boolean) => {
      if (!additive) {
        onSelectPids([pid], "replace");
        return;
      }
      if (selectedPids.has(pid)) {
        onSelectPids([...selectedPids].filter((x) => x !== pid), "replace");
        return;
      }
      onSelectPids([pid], "add");
    },
    [onSelectPids, selectedPids]
  );

  /**
   * ⭐⭐ R14 (W50-T14) REWROTE THREE OF THIS LABEL'S FOUR BRANCHES, because they described a
   * gesture the pin no longer has. Until 2026-09-03 a plain click with the Routes panel open
   * asked to add or remove a stop instead of opening the record, and this label promised exactly
   * that. R14 retired the shortcut, so `openHint` is now UNCONDITIONAL and leads every branch:
   * click or Enter opens the record whatever else is on screen.
   *
   * β›” NO BRANCH MAY PROMISE THE MEMBERSHIP PROMPT AGAIN. What the Route-mode branches still say
   * is a FACT about the active route (no route open, read-only, already a stop or not) plus where
   * the two visible membership doors are; none of them claims the pin itself edits the route.
   * Policed by `verify_ui.py::pin_label_states_the_gesture` and `verify_map.py`'s `truthful-copy`.
   */
  const pinAriaLabel = useCallback((point: MapPoint) => {
    const title = point.title || "Untitled record";
    if (pinClickSelects) {
      const selection = selectedPids.has(point.pid) ? "Selected." : "Not selected.";
      return `${title}. ${selection} Click a pin to select it. Shift-click to add or remove it. Double-click or press Enter to open the record. Press Space to select.`;
    }
    const openHint = "Click or press Enter to open the record.";
    const selectionHint = "Shift-click or press Space to select.";
    if (!routePanelOpen)
      return `${title}. ${openHint} ${selectionHint}`;
    if (!activeNamedRoute)
      return `${title}. ${openHint} No route is open, so route stops cannot be changed. Open a route first. ${selectionHint}`;
    if (!activeNamedRoute.permission.canEdit)
      return `${title}. ${openHint} ${activeNamedRoute.name} is read-only, so its stops cannot be changed. ${selectionHint}`;
    const action = activeNamedRoute.visibleStopIds.includes(point.pid) ? "remove" : "add";
    return `${title}. ${openHint} ${action === "remove" ? `A stop on ${activeNamedRoute.name}. Use the route panel to remove it.` : `Not a stop on ${activeNamedRoute.name}. Use the route panel to add it.`} ${selectionHint}`;
  }, [activeNamedRoute, routePanelOpen, pinClickSelects, selectedPids]);

  const onPointerUp = useCallback(
    (e: ReactPointerEvent<SVGSVGElement>) => {
      // W46-T28 β€” the reshape lands the same way a boundary move does: the draft geometry the
      // pointer built is what gets persisted, and the draft is cleared either way so a failed
      // save cannot leave the map showing a shape the server never accepted.
      if (zoneVertex) {
        const geometry = zoneGeometryDraft?.id === zoneVertex.zone.id
          ? zoneGeometryDraft.geometry
          : null;
        setZoneVertex(null);
        setZoneGeometryDraft(null);
        if (geometry) void persistZoneGeometry(zoneVertex.zone, geometry);
        if (e.currentTarget.hasPointerCapture(e.pointerId))
          e.currentTarget.releasePointerCapture(e.pointerId);
        return;
      }
      if (zoneMove) {
        const geometry = zoneGeometryDraft?.id === zoneMove.zone.id
          ? zoneGeometryDraft.geometry
          : null;
        setZoneMove(null);
        setZoneGeometryDraft(null);
        if (geometry) void persistZoneGeometry(zoneMove.zone, geometry);
        if (e.currentTarget.hasPointerCapture(e.pointerId))
          e.currentTarget.releasePointerCapture(e.pointerId);
        return;
      }
      // ⭐ W46-T17 β€” a click that did not travel places a vertex. It sits above
      // the marquee branch so an armed drawing owns the plain click, and below
      // `zoneMove` so dragging an existing Zone still wins. `movedRef` is the
      // same "this was a drag, not a click" rule the pins use, so a pan while
      // armed still pans and drops nothing.
      // β›” `zoneKeyboardDraft` IS IN THIS CALLBACK'S DEPENDENCY ARRAY and must
      // stay there: without it, arming the tool changes no dependency, the
      // memoized closure keeps reading `null`, and the first clicks after
      // arming silently do nothing until some other dependency happens to
      // change. That intermittency is exactly what the bug reported.
      if (zoneKeyboardDraft && view && !drag && !movedRef.current) {
        addZoneDraftVertex(localPoint(e.clientX, e.clientY));
        panRef.current = null;
        if (e.currentTarget.hasPointerCapture(e.pointerId))
          e.currentTarget.releasePointerCapture(e.pointerId);
        return;
      }
      if (drag && view) {
        // A gesture smaller than a few px is a mis-click, not a selection β€”
        // clearing the user's set on a stray shift-click would be its own bug.
        // ONE rule for both shapes, measured on the lasso's own bounds; a loop
        // also needs three points before it is a polygon at all.
        const b =
          drag.kind === "rect"
            ? normRect(drag.x0, drag.y0, drag.x1, drag.y1)
            : pathBounds(drag.pts);
        const drawn = b.x1 - b.x0 > 3 && b.y1 - b.y0 > 3 && (drag.kind === "rect" || drag.pts.length >= 3);
        if (drawn) {
          const hits: number[] = [];
          for (const p of points) {
            const s = toScreen(p.p, view);
            const held =
              drag.kind === "rect"
                ? s.x >= b.x0 && s.x <= b.x1 && s.y >= b.y0 && s.y <= b.y1
                : pointInPolygon(s, drag.pts);
            if (held) hits.push(p.pid);
          }
          onSelectPids(hits, e.altKey ? "add" : "replace");
          // A selection gesture is also a deliberate geographic outline. Keep its exact
          // lon/lat geometry ready for C3's Save Zone action; the membership snapshot above
          // remains the answer to "which current records were in it".
          if (zoneEditorOpen && zoneDrawShape === "circle") {
            const centerScreen = { x: (b.x0 + b.x1) / 2, y: (b.y0 + b.y1) / 2 };
            const edgeScreen = { x: b.x1, y: centerScreen.y };
            const center = unproject(fromScreen(centerScreen, view));
            const edge = unproject(fromScreen(edgeScreen, view));
            setDrawnZoneGeometry({
              type: "Circle",
              center: [center.lon, center.lat],
              radiusMeters: Math.max(1, Math.round(haversineKm(
                { lat: center.lat, lon: center.lon }, { lat: edge.lat, lon: edge.lon }
              ) * 1000)),
            });
          } else {
            const outline = drag.kind === "rect"
              ? [
                  { x: b.x0, y: b.y0 }, { x: b.x1, y: b.y0 },
                  { x: b.x1, y: b.y1 }, { x: b.x0, y: b.y1 },
                ]
              : drag.pts;
            const coordinates = outline
              .map((screen) => unproject(fromScreen(screen, view)))
              .map(({ lon, lat }) => [lon, lat]);
            if (coordinates.length >= 3)
              setDrawnZoneGeometry({ type: "Polygon", coordinates: [[...coordinates, coordinates[0]]] });
          }
        }
        setDrag(null);
      }
      panRef.current = null;
      if (e.currentTarget.hasPointerCapture(e.pointerId))
        e.currentTarget.releasePointerCapture(e.pointerId);
    },
    [drag, view, points, onSelectPids, zoneMove, zoneVertex, zoneGeometryDraft, persistZoneGeometry,
      zoneDrawShape, zoneEditorOpen, zoneKeyboardDraft, addZoneDraftVertex, localPoint]
  );

  /**
   * ⭐⭐ W37-T37 β€” THE LOOKUP CONTROL IS BUILT ONCE AND RENDERED IN TWO PLACES, and the second
   * place is the whole reason this is a variable rather than inline JSX.
   *
   * β›” IT SHIPPED UNREACHABLE THE FIRST TIME AND ONLY LOOKING FOUND IT. The control lived in the
   * map bar; the bar lives after the `!view || !fit` early return below; and a database whose
   * records have addresses and no coordinates has NO POINTS, so it takes that return. The feature
   * was therefore invisible in precisely the situation it exists for, and visible only once you no
   * longer needed it. Every gate was green: the door scan found the control, `tsc` was clean, and
   * the component rendered. [[reachable-is-not-the-same-as-built]] is this exact shape.
   */
  const geoControl = coordField?.geocode?.addressField && (onGeocoded || geocodeSessionOnly) ? (
    <span className="cg-map-geo">
      {geo.busy ? (
        <>
          <span className="cg-map-geo-run">
            Looking up addresses: <strong>{geo.done.toLocaleString()}</strong> of{" "}
            {geo.total.toLocaleString()}
          </span>
          {/* ⚠ The rate limit is a LICENCE TERM here, not a performance excuse, so the surface
              says why it is slow instead of letting it read as a hang. */}
          <span className="cg-map-geo-note">
            about one address a second, which is what the free map service allows
          </span>
        </>
      ) : geocodable.length > 0 ? (
        <button
          type="button"
          className="cg-btn cg-map-geo-cta"
          onClick={() => void runGeocode()}
          title={geocodeSessionOnly
            ? `Look up ${geocodable.length.toLocaleString()} address${
                geocodable.length === 1 ? "" : "es"
              } and place the records on this map. Takes ${geoEstimate}.`
            : `Look up ${geocodable.length.toLocaleString()} address${
                geocodable.length === 1 ? "" : "es"
              } and fill ${coordField.label}. Takes ${geoEstimate}.`}
        >
          Look up {geocodable.length.toLocaleString()} address
          {geocodable.length === 1 ? "" : "es"} ({geoEstimate})
        </button>
      ) : null}
      {!geo.busy && geo.total > 0 && (
        <span className="cg-map-geo-note">
          Located {geo.found.toLocaleString()} of {geo.total.toLocaleString()}
          {geo.found < geo.total && ". The rest had no address on file or could not be matched."}
          {geocodeSessionOnly && geo.found > 0 && " These locations stay on this map for this session."}
        </span>
      )}
      {geo.error && <span className="cg-cal-nodate">{geo.error}</span>}
    </span>
  ) : null;

  const renderHeader = (barActions?: ReactNode) => {
    // The Routing frame carries the App mark and the Odoo mark; a plain map bar carries neither.
    const actions = routeApplication && applicationName
      ? <><AppFrameMarks mark="route" connector="odoo" />{barActions}</> : barActions;
    return routeApplication && applicationName
      ? <AppFrame appName={applicationName} actions={actions} />
      : <div className="cg-map-bar">{actions}</div>;
  };

  if (!view || !fit) {
    const empty = (
      <div className="cg-mode-empty">
        {geocodeSessionOnly
          ? "No records with a location to map yet."
          : "No records with a location to map yet. Set latitude and longitude fields in View schema to plot records."}
        {/* The way OUT of the empty state, offered from inside it. Selecting records and looking
            up their addresses is the one action that turns this screen into a map. */}
        {geoControl && <div className="cg-map-geo-empty">{geoControl}</div>}
        {geoControl && geocodable.length === 0 && selectedPids.size === 0 && (
          <div className="cg-map-geo-note">
            Select the records you want placed, then look up their addresses.
          </div>
        )}
      </div>
    );
    return routeApplication && applicationName
      ? <div className="cg-mapview cg-app-route-surface">
          {renderHeader(routingFilters && <div className="cg-routing-filter-bar">{routingFilters}</div>)}
          {empty}
        </div>
      : empty;
  }

  const hovered = hoverPid != null ? points.find((p) => p.pid === hoverPid) : undefined;
  const rect = drag?.kind === "rect" ? normRect(drag.x0, drag.y0, drag.x1, drag.y1) : null;
  const lassoPts = drag?.kind === "lasso" && drag.pts.length > 1 ? drag.pts : null;
  // ⭐ ITEM 1 β€” `rotate` sits BETWEEN the translate and the scale, which is the transform
  // `toScreen` computes and `fromScreen` inverts (`t + R . k . p`, read right to left). Any other
  // order paints a map whose pins, hit tests and hover cards disagree about where things are.
  const tf =
    `translate(${view.tx.toFixed(2)} ${view.ty.toFixed(2)}) ` +
    `rotate(${(view.rot ?? 0).toFixed(2)}) scale(${view.k.toFixed(6)})`;
  // Strokes live in the transformed group, so they are pre-divided by the zoom.
  // ⚠ This is the map's ONE stroke mechanism β€” see the note over `hairline` in
  // mapProjection.ts. No `.cg-map*` rule may add `vector-effect:
  // non-scaling-stroke` on top; that double-cancel is the wave-9 blur bug and
  // `scalingConflicts()` gates the stylesheet against it.
  const hair = (w: number) => hairline(w, view.k);
  /**
   * β›” W47-T03 β€” THE UNSAVED SHAPE AND THE CONTROLS THAT OWN IT SHARE ONE CONDITION, and it is
   * this literal expression rather than `zoneEditorOpen` alone because the Zone editor aside is
   * gated on all three. `drawnZoneGeometry` SURVIVES "Back to Zones" and a switch to the Routes
   * tab, so painting on `zoneEditorOpen` alone would leave a dashed boundary on the map with no
   * Save zone and no Discard anywhere on screen: an unsaved state nobody can resolve, which is
   * instruction 20's confusion wearing the opposite mask.
   *
   * β›” AND THE RENDER SITE ADDS `!zoneKeyboardDraft` ON TOP OF THIS, exactly as the panel row
   * does, because `startKeyboardZoneDrawing` does NOT clear `drawnZoneGeometry` β€” the clears live
   * in `beginNewZone`, `beginEditZone` and `saveZone` only. Finish a shape, then choose "Draw by
   * clicking" again, and the panel row hides itself while the dashed boundary would have stayed
   * painted with no control anywhere: the same orphan through the other door. Both sides must
   * read `zoneEditorPanelOpen && !zoneKeyboardDraft && <geometry>` or they drift apart again.
   *
   * β›” W51-T28 MOVED THE DECLARATION UP, IT DID NOT ADD A SECOND ONE. `useEscapeClose` has to
   * register above the `!view || !fit` early return, so `zoneEditorPanelOpen` and its chooser
   * sibling now live beside those hooks. Declaring the expression twice is exactly the drift this
   * comment warns about, so there is one const and both the Escape claim and the render sites
   * read it.
   */
  const gratOpacity = graticuleOpacity(view.k);
  // I18 β€” the Google hand-off, and W37-T35 changed what it is FOR.
  // It used to be the answer to "I need to see the actual street", because the
  // vendored basemap stopped at roughly metro scale. Real tiles go to street
  // level themselves, so this link is no longer an apology for a missing
  // capability: it is a hand-off to a tool that does routing, transit and
  // street imagery, which this view does not.
  // ⚠ The old note here read "Nothing is fetched and no coordinate leaves the
  // page unless the user deliberately clicks". The second half still holds and
  // is the part that matters: a tile request carries a z/x/y grid square and
  // never a record. The first half does not, and is corrected in the header.
  const centre = unproject(fromScreen({ x: VIEW_W / 2, y: VIEW_H / 2 }, view));
  const areaUrl = googleMapsUrl(centre.lat, centre.lon, googleZoomForK(view.k));
  const sizeDomain = sizeRange && !sizeRange.none && sizeRange.max > sizeRange.min
    ? magnitudeDomain(sizeRange.min, sizeRange.max)
    : null;
  const sizeLegend = sizeDomain ? [sizeDomain.lo, (sizeDomain.lo + sizeDomain.hi) / 2, sizeDomain.hi] : null;
  const navigatorTabs = (
    <div className="cg-map-navigator-tabs" role="tablist" aria-label="Map assets">
      <button type="button" role="tab" aria-selected={mapNavigator === "routes"}
        onClick={() => { setZoneNavigatorOpen(false); setZoneEditorOpen(false); }}>
        Routes
      </button>
      <button type="button" role="tab" aria-selected={mapNavigator === "zones"}
        onClick={() => { setZoneNavigatorOpen(true); setActiveRouteId(null); }}>
        Zones
      </button>
    </div>
  );

  return (
    <div
      className={"cg-mapview" + (routeApplication ? " cg-app-route-surface" : "")}
      /* Both custom properties, from ONE number. The unsaved shape stays exactly half, which is
         the invariant `map-panels.css` says has already survived three retunes. */
      style={{
        "--lp-zone-fill": String(zoneFillOpacity),
        "--lp-zone-fill-unsaved": String(zoneFillOpacity / 2),
      } as React.CSSProperties}
    >
      {renderHeader(<>
        {routeApplication && routingFilters && <div className="cg-routing-filter-bar">{routingFilters}</div>}
        {/* The count is "N of M", never a bare N: a pin can only be drawn for a
            row the host geocoded, and a lone "1,402" silently redefines the
            toolbar's 1,550 ([[no-unverifiable-aggregates]]). */}
        <span className="cg-cal-note cg-map-count">
          <span><strong>{points.length.toLocaleString()}</strong> of {mapRows.length.toLocaleString()} mapped</span>
        </span>
        {routeSelectionWarning && !routePanelOpen && (
          <aside className="cg-route-popover" aria-label="Route selection notice">
            <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
          </aside>
        )}
        {geoControl}
        {/* Every gesture the map has, named. `alt` (add to the selection rather
            than replace it, onPointerUp) shipped in wave 8 and was disclosed
            NOWHERE, so "select these as well" was a feature only the source
            knew about. It needs shift too β€” alt alone still pans. */}
        <span className="cg-map-hint">
          {pinClickSelects ? <>
          Click a pin to select Β· shift-click to add or remove Β· double-click or press Enter to open
          Β· scroll to zoom Β· drag to pan Β· {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}
          {" "}Β· shift-alt-drag to extend the selection
          </> : routeApplication ? "Click to open Β· scroll to zoom" : <>
          Scroll to zoom Β· drag to pan Β· {lassoTool ? "shift-drag to lasso" : "shift-drag to select"}{" "}
          Β· shift-alt-drag to extend the selection Β· click or press Enter on a pin to open the
          record Β· shift-click or press Space on a pin to add or remove it from the selection
          </>}
        </span>
      </>)}
      {/* ⭐⭐ W51-T32 - THE MAP AND THE 380 px ROUTE COLUMN SHARE ONE FLEX ROW, WHICH IS WHY
          THE THREE NAVIGATOR PANELS MOVED OUT OF THE TOOLBAR. They used to be toolbar children
          floated over the canvas, and the mechanism that made that unfixable is document order
          inside an SVG: a pin painted under the floating column could not receive a pointer
          event, and no stacking value on either side changes that. Wave 50's QA measured 427 px
          of live map covered and a coordinate click on a covered pin opening nothing at all.
          The repair is LAYOUT: the canvas and the column are siblings in a row, the canvas
          yields the width the column takes, and every pin is back in the open.
          ⚠ The row also RETIRES four competing declarations in three other stylesheets, all of
          them keyed on the toolbar-child path, so they simply stop matching rather than needing
          an override this ticket is not allowed to write.
          ⚠ The frame block below deliberately keeps its former indentation. Re-indenting 820
          lines would bury a structural move in a whitespace diff and would rewrite two
          multi-line template literals inside it. */}
      <div className="cg-map-stage">
      {/* ⭐⭐ W41-T48 β€” OPENING A RECORD FOLDS THE RAIL, and R14 (2026-09-03) removed the
          `!routePanelOpen` gate from this frame's `onPointerDown`. That gate existed only because
          a pin click in Route mode did not open a record; it now does, on every pin, so the map
          must fold the rail in Route mode exactly as it does outside it. */}
      <div
        ref={mapFrameRef}
        className="cg-map-frame"
        tabIndex={0}
        role="group"
        aria-label={zoneKeyboardDraft
          ? `Zone ${zoneKeyboardDraft.shape} drawing canvas. Click the map to add points, then press Enter to finish.`
          : "Map canvas. Arrow keys pan, plus and minus zoom, square brackets rotate, zero fits to data and faces north."}
        onKeyDown={onFrameKeyDown}
        // Inline App detail preserves the rail. Data openings keep their minimization event.
        onPointerDown={() => { if (!routeApplication) signal(NAV_MINIMIZE_EVENT); }}
      >
        <svg
          ref={setSvgEl}
          viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}
          preserveAspectRatio="xMidYMid meet"
          className={"cg-map-svg" + (drag ? " is-selecting" : "")}
          role="img"
          aria-label={`Map of ${points.length.toLocaleString()} records`}
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerUp}
          onPointerCancel={onPointerUp}
        >
          <rect className="cg-map-water" x={0} y={0} width={VIEW_W} height={VIEW_H} />
          <g transform={tf}>
            {/* --- W37-T35: the raster basemap, UNDER everything, inside the same transform.
                β›” AND THE VENDORED GEOMETRY BELOW IS HIDDEN WHILE IT PAINTS. Drawing a
                generalised coastline on top of a real one does not add detail, it adds a SECOND
                coastline a few pixels off the first, plus a graticule fighting the tiles' own
                grid. Two basemaps disagreeing about where Florida is looks like a rendering bug
                to everyone except the person who knows there are two of them. --- */}
            {tileLayer && (
              <g className="cg-map-tiles" aria-hidden="true">
                {/* Painted under the images so a tile still in flight shows map-coloured ground
                    rather than the page behind it, which reads as a hole rather than as loading. */}
                <rect
                  className="cg-map-tilebed"
                  x={tileLayer.bed.x}
                  y={tileLayer.bed.y}
                  width={tileLayer.bed.w}
                  height={tileLayer.bed.h}
                />
                {tileLayer.items.map((t) => (
                  <image
                    key={t.key}
                    className="cg-map-tile"
                    href={t.href}
                    x={t.x}
                    y={t.y}
                    width={t.s}
                    height={t.s}
                    preserveAspectRatio="none"
                    // The fallback's trigger. A tile 404 at the edge of coverage is ordinary, so
                    // this counts rather than switches; TILE_FAIL_LIMIT decides.
                    onError={() => setTileFails((f) => f + 1)}
                  />
                ))}
              </g>
            )}
            {/* Graticule every 10 degrees. It earns its place zoomed OUT, where
                it is the only thing giving scale; once the real state borders
                arrive it would be a second line system fighting the first, so it
                fades away before they take over. Skipped entirely at zero
                opacity β€” ~36 invisible lines are still 36 nodes to lay out. */}
            {!tileLayer && gratOpacity > 0.01 && (
              <g className="cg-map-grat" strokeWidth={hair(0.6)} opacity={gratOpacity}>
              {Array.from({ length: 17 }, (_, i) => {
                const y = project(0, -80 + i * 10).y;
                return <line key={`p${i}`} x1={0} y1={y} x2={WORLD} y2={y} />;
              })}
              {Array.from({ length: 19 }, (_, i) => {
                const x = project(-180 + i * 20, 0).x;
                return <line key={`m${i}`} x1={x} y1={0} x2={x} y2={WORLD} />;
              })}
              </g>
            )}
            {/* One path, every US state ring. Filled AND stroked, so interior
                state borders come free from the same geometry β€” no second pass
                and no chance of the borders disagreeing with the coastline.
                0.9 rather than wave 8's 1.1: that weight was tuned for a single
                lone coastline, and it reads heavy once ~169 rings share it. */}
            {!tileLayer && (
              <>
                <path className="cg-map-land" d={LAND_PATH} strokeWidth={hair(0.9)} />
                {LAKE_PATHS.map((d, i) => (
                  <path key={i} className="cg-map-lake" d={d} strokeWidth={hair(0.8)} />
                ))}
              </>
            )}
            {/* β›”β›” W47-T02 CAUSE 1, RENDER SITE 1 OF 4. `fill={ring.zone.color}` had no fallback
                and an unset SVG `fill` paints BLACK, which is the boundary-shaped half of the
                owner's "Huge Blob". Every fill and stroke goes through `zonePaint`. */}
            {zonePolygons.map((ring) => (
              <polygon
                key={ring.key}
                className="cg-map-zone"
                points={ring.points.map((point) => `${point.x.toFixed(2)},${point.y.toFixed(2)}`).join(" ")}
                fill={zonePaint(ring.zone.color)}
                stroke={zonePaint(ring.zone.color)}
                strokeWidth={hair(LP_ZONE_STROKE_WIDTH)}
                tabIndex={0}
                role="button"
                aria-label={`${ring.zone.name} Zone. Enter selects records; arrow keys move the boundary.`}
                onKeyDown={(event) => {
                  if (event.key === "Enter" || event.key === " ") {
                    event.preventDefault(); onSelectPids(ring.zone.memberships, "replace"); return;
                  }
                  const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 }
                    : event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 }
                    : event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 }
                    : event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null;
                  if (!delta) return;
                  event.preventDefault(); void persistZoneGeometry(ring.zone, translateZoneGeometry(ring.geometry, delta));
                }}
                onPointerDown={(event) => {
                  // W46-T17 β€” an armed drawing owns the pointer; dragging a saved
                  // boundary would otherwise eat the click meant for a vertex.
                  if (event.button !== 0 || !view || zoneKeyboardDraft) return;
                  event.stopPropagation();
                  movedRef.current = false;
                  const svg = event.currentTarget.ownerSVGElement;
                  svg?.setPointerCapture(event.pointerId);
                  setZoneMove({
                    zone: ring.zone,
                    geometry: ring.geometry,
                    start: localPoint(event.clientX, event.clientY),
                  });
                }}
                onClick={(event) => {
                  if (zoneKeyboardDraft) return;
                  event.stopPropagation();
                  if (movedRef.current) {
                    movedRef.current = false;
                    return;
                  }
                  if (!activeZoneIds.has(ring.zone.id)) toggleZone(ring.zone, true);
                  else onSelectPids(ring.zone.memberships, "replace");
                }}
              >
                <title>{`${ring.zone.name}: click to select records, drag to move boundary`}</title>
              </polygon>
            ))}
            {/* β›”β›” W47-T02, RENDER SITE 2 OF 4, AND THE ONE SITE THAT CARRIES BOTH CAUSES.
                CAUSE 1: `fill={zone.color}` had no fallback, so a colourless circle Zone painted
                black. CAUSE 2: `r={radius}` was the raw projected `Math.abs(edge.x - center.x)`
                with no clamp, so an absurd `radiusMeters` painted a disc over the whole canvas.
                The two are independent and neither is redundant - see `zonePaint` and
                `clampZoneRadius`. The clamp takes `view.k` because `r` lives inside `tf`. */}
            {zoneCircles.map(({ zone, geometry, center, radius }) => (
              <circle key={zone.id} className="cg-map-zone" cx={center.x} cy={center.y} r={clampZoneRadius(radius, view.k)}
                fill={zonePaint(zone.color)} stroke={zonePaint(zone.color)} strokeWidth={hair(LP_ZONE_STROKE_WIDTH)} tabIndex={0} role="button"
                aria-label={`${zone.name} Circle Zone. Enter selects records; arrow keys move the boundary.`}
                onPointerDown={(event) => { if (event.button !== 0 || !view || zoneKeyboardDraft) return; event.stopPropagation(); movedRef.current = false; event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId); setZoneMove({ zone, geometry, start: localPoint(event.clientX, event.clientY) }); }}
                onClick={(event) => { if (zoneKeyboardDraft) return; event.stopPropagation(); if (movedRef.current) { movedRef.current = false; return; } onSelectPids(zone.memberships, "replace"); }}
                onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onSelectPids(zone.memberships, "replace"); return; } const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 } : event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 } : event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 } : event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null; if (delta) { event.preventDefault(); void persistZoneGeometry(zone, translateZoneGeometry(geometry, delta)); } }}>
                <title>{`${zone.name}: circle radius ${Math.round(geometry.radiusMeters)} metres`}</title>
              </circle>
            ))}
            {/* β›”β›” W47-T03 β€” THE RENDER `drawnZoneGeometry` NEVER HAD. This is the whole of
                owner instruction 20: finishing a shape moved it into a state nothing drew, so
                the boundary vanished the instant it became real and only came back as a SAVED
                Zone. It is dashed and lighter than a saved boundary because unsaved is a STATE
                the user has to be able to read at a glance, not a difference they must infer.
                ⚠ THE DASH IS AN ATTRIBUTE, NOT A CSS RULE. Everything in this group is
                pre-divided by the zoom through `hair`, so a `stroke-dasharray` declared in user
                units would grow with the camera; `vector-effect: non-scaling-stroke` is the
                other way to fix that and `verify_map.py`'s `map-css-no-non-scaling-stroke` leg
                reds on it. The fill opacity stays in CSS, beside `--lp-zone-fill`.
                ⚠ `aria-hidden`, and the state is announced instead by the `role="status"` line
                over the Save zone / Discard pair: a decorative outline that is `pointer-events:
                none` is not something a screen reader can act on, and the sentence is. */}
            {zoneEditorPanelOpen && !zoneKeyboardDraft && unsavedZoneShape && (
              <g className="cg-map-zone-unsaved" aria-hidden="true">
                {unsavedZoneShape.kind === "circle" ? (
                  <circle
                    cx={unsavedZoneShape.center.x}
                    cy={unsavedZoneShape.center.y}
                    r={clampZoneRadius(unsavedZoneShape.radius, view.k)}
                    fill={zonePaint(zoneColor)}
                    stroke={zonePaint(zoneColor)}
                    strokeWidth={hair(1.8)}
                    strokeDasharray={`${hair(7)} ${hair(5)}`}
                  />
                ) : unsavedZoneShape.rings.map((points, index) => (
                  <polygon
                    key={index}
                    points={points}
                    fill={zonePaint(zoneColor)}
                    stroke={zonePaint(zoneColor)}
                    strokeWidth={hair(1.8)}
                    strokeDasharray={`${hair(7)} ${hair(5)}`}
                  />
                ))}
              </g>
            )}
            {/* ⭐⭐ W46-T28 β€” THE VERTEX HANDLES. Owner instruction 16: *"the zone vertices
                should be a dot that is draggable so I can minimize or expand a zone."* Dragging
                the boundary itself already MOVED a Zone; nothing could change its SHAPE.
                β›” THEY MOUNT HERE, INSIDE `<g transform={tf}>`, AND NOT IN THE DRAFT GROUP.
                `.cg-zone-keyboard-draft` is `pointer-events: none` (map-panels.css, W46-T17) so
                the in-progress outline cannot swallow the clicks that extend it. A dot placed in
                there would be equally unhittable, which is the whole feature. Living inside the
                camera transform also means a handle stays on its corner through every pan,
                zoom and rotation for free.
                β›” AND THEY ARE HIDDEN WHILE DRAWING IS ARMED. T17 made a plain click add a
                vertex to the NEW shape; leaving old handles on top of that would eat those
                clicks and re-break the bug that ticket just fixed.
                Only polygons: a circle has no vertices, and resizing one is its own control. */}
            {!zoneKeyboardDraft && zonePolygons.flatMap((ring) => (
              normalizedCustomerZones && !ring.zone.permission?.canEdit ? [] :
              // β›”β›” AND A LASSO-DRAWN BOUNDARY GETS NO HANDLES, DELIBERATELY. A rectangle
              // marquee stores 4 corners, a clicked outline stores what the user clicked, but
              // the lasso stores EVERY SAMPLED POINTERMOVE: hundreds of coordinates. A dot on
              // each would be a solid ring of dots hiding the very fill this ticket exists to
              // make legible, and hundreds of tab stops rebuilt on every pointermove. A corner
              // you cannot tell apart from its neighbour is not a handle anyway.
              // ⚠ REPORTED, NOT SILENT (standing rule 1): the limit is named here and in the
              // ticket handoff, and the whole-boundary drag and the arrow keys still reach
              // those Zones. Lifting it needs vertex simplification, which is its own ticket.
              ring.handles.length > ZONE_VERTEX_HANDLE_MAX ? [] :
              /* β›” W47-T02 CAUSE 1, RENDER SITE 4 OF 4 - FOUND BY THE GATE, NOT BY THE SPEC. The
                 ticket named two zone shapes, a third was already live in the draft preview, and
                 this vertex dot is a FOURTH: it painted black on a colourless Zone exactly like
                 the rest. Its `r` is `hair(5)`, already bounded, so only cause 1 reaches here.
                 THIS is why the normaliser is one named helper rather than `|| X` sprinkled over
                 individual attributes - a per-site fix would have missed this site too. */
              ring.handles.map((point) => (
                <circle
                  key={`${ring.key}:v${point.vertexIndex}`}
                  className="cg-map-zone-vertex"
                  cx={point.x}
                  cy={point.y}
                  r={hair(5)}
                  fill={zonePaint(ring.zone.color)}
                  stroke={LP_INK}
                  strokeWidth={hair(LP_ZONE_STROKE_WIDTH)}
                  tabIndex={0}
                  role="button"
                  aria-label={`${ring.zone.name} boundary point ${point.vertexIndex + 1}. Drag it, or use the arrow keys, to reshape the Zone.`}
                  onPointerDown={(event) => {
                    if (event.button !== 0 || !view) return;
                    // The boundary under this dot has its own drag. Stopping here is what makes
                    // the handle the more specific target rather than a decoration on top of it.
                    event.stopPropagation();
                    movedRef.current = false;
                    event.currentTarget.ownerSVGElement?.setPointerCapture(event.pointerId);
                    setZoneVertex({
                      zone: ring.zone,
                      geometry: ring.geometry,
                      polygonIndex: ring.polygonIndex,
                      ringIndex: ring.ringIndex,
                      vertexIndex: point.vertexIndex,
                    });
                  }}
                  onClick={(event) => { event.stopPropagation(); movedRef.current = false; }}
                  onKeyDown={(event) => {
                    const delta = event.key === "ArrowLeft" ? { lon: -0.0005, lat: 0 }
                      : event.key === "ArrowRight" ? { lon: 0.0005, lat: 0 }
                      : event.key === "ArrowUp" ? { lon: 0, lat: 0.0005 }
                      : event.key === "ArrowDown" ? { lon: 0, lat: -0.0005 } : null;
                    if (!delta || !view) return;
                    event.preventDefault();
                    event.stopPropagation();
                    const source = unproject(fromScreen(point, view));
                    void persistZoneGeometry(ring.zone, moveZoneVertex(ring.geometry, {
                      polygonIndex: ring.polygonIndex,
                      ringIndex: ring.ringIndex,
                      vertexIndex: point.vertexIndex,
                    }, { lon: source.lon + delta.lon, lat: source.lat + delta.lat }));
                  }}
                >
                  <title>{`${ring.zone.name}: drag this point to reshape the Zone`}</title>
                </circle>
              ))
            ))}
            {/* The planned path, UNDER the pins so it never hides a stop. Inside
                the zoomed group, so it pans and scales with the geography; the
                stroke is pre-divided by k like every other line here. */}
            {/* ⭐ W37-T36 β€” THE ROAD, drawn from the service's own geometry. Two claims about the
                same stops need two looks: this is solid and follows streets, the dashed line below
                is the straight-line plan and stays provisional. A white halo underneath, because a
                navy line over a raster basemap full of navy roads is invisible exactly where
                somebody is trying to read it.
                ⚠ Greyed rather than removed when stale: it still describes a real route, just not
                the one currently listed, and hiding it would lose the picture the moment somebody
                nudges one stop. */}
            {roadPath && (
              <g className={"cg-map-roadwrap" + (roadStale ? " is-stale" : "")}
                 opacity={roadStale ? 0.35 : 1}>
                <polyline className="cg-map-road-halo" strokeWidth={hair(5.5)} points={roadPath} />
                <polyline className="cg-map-road" strokeWidth={hair(2.6)} points={roadPath} />
              </g>
            )}
            {plan && plan.ordered.length > 1 && (
              <polyline
                className="cg-map-route-line"
                strokeWidth={hair(1.8)}
                // ⚠ The dash MUST be pre-divided by the zoom too β€” a CSS
                // dasharray is in user units and would scale with the group,
                // turning the route into a few disconnected strokes.
                strokeDasharray={dashPattern(5, 4, view.k)}
                points={
                  plan.ordered.map((p) => `${p.p.x},${p.p.y}`).join(" ") +
                  (roundTrip ? ` ${plan.ordered[0].p.x},${plan.ordered[0].p.y}` : "")
                }
              />
            )}
            {/* ⭐ W47-T07: the ticked routes, each in its own persisted colour. Drawn BEFORE the
                pins so a pin is never hidden under a line, and after `plan` so the route a person
                actually opened stays the emphasised one. */}
            {overlaidRoutes.map((overlay) => (
              <polyline
                key={overlay.id}
                className="cg-map-route-overlay"
                fill="none"
                stroke={overlay.color}
                strokeWidth={hair(2.2)}
                points={overlay.pts.map((at) => `${at.x},${at.y}`).join(" ")}
              />
            ))}
            {points.map((p) => {
              const c = paint(p);
              const on = selectedPids.has(p.pid) || customerDetail?.pid === p.pid;
              const r = radius(p) / view.k;
              return (
                <circle
                  key={p.pid}
                  data-map-pid={p.pid}
                  className={
                    "cg-map-pin" +
                    (hoverPid === p.pid ? " is-hover" : "") +
                    (on ? " is-selected" : "")
                  }
                  cx={p.p.x}
                  cy={p.p.y}
                  r={hoverPid === p.pid ? r * 1.28 : r}
                  // ⭐ SELECTED IS A FILL CHANGE, NOT ONLY A RING (wave 41 item 18). The ring
                  // alone left a selected pin on a mid-tone swatch hard to pick out, so the fill
                  // moves to the one blue reserved for selection. Both values are NAMED tokens
                  // carried in `theme.ts`; see `LP_MAP_SELECTED` for why this exact blue and why
                  // the product primary is not it.
                  // ⚠ THE COST, ACCEPTED: while a pin is selected it stops showing its colour-by
                  // bucket. The HOVER CARD is what still carries that value: it prints
                  // `colorField.label` from `hovered.colorVal`, which is on MapPoint for exactly
                  // this. The legend does NOT rescue it, since a legend maps buckets to colours
                  // and cannot say which bucket THIS pin is in. One unmistakable selection is
                  // what the ruling asked for.
                  fill={on ? LP_MAP_SELECTED : c.fill}
                  stroke={on ? LP_INK : c.line}
                  strokeWidth={hair(on ? 2 : 1)}
                  role="button"
                  tabIndex={0}
                  // β›”β›” NO `aria-pressed` HERE, AND THE ABSENCE IS THE FIX (W46-T14 / D-419).
                  // Do not "restore" it in an a11y sweep. `aria-pressed` declares a TOGGLE
                  // button, whose default activation flips a state. After R10 (W38-T09) a
                  // plain click on a pin OPENS THE RECORD; only a modifier click or Space
                  // moves the selection. So the pressed state, while it tracked selection
                  // correctly, told a screen reader the wrong thing about the one gesture it
                  // would try. The selected/unselected fact is not lost: `pinAriaLabel` below
                  // states it in words, along with both gestures, which is the channel that
                  // matches what the control actually does.
                  // β›” THE ACCESSIBLE NAME IS THE ONLY CHANNEL A NON-SIGHTED USER HAS FOR A PIN'S
                  // gesture: a `<circle>` carries no tooltip, no hover card and no glyph, and the
                  // hint bar above is the SIGHTED half of this same disclosure. It said "Click to
                  // select, double click to open." until R10 made that false.
                  // Policed by `verify_ui.py::pin_label_states_the_gesture`.
                  aria-label={pinAriaLabel(p)}
                  onMouseEnter={() => setHoverPid(p.pid)}
                  onMouseLeave={() => setHoverPid((h) => (h === p.pid ? null : h))}
                  onFocus={() => setHoverPid(p.pid)}
                  onBlur={() => setHoverPid((h) => (h === p.pid ? null : h))}
                  onClick={(e) => {
                    // ⭐ W46-T17 β€” while Zone drawing is armed the map is a drawing
                    // surface, so a click that lands on a pin places a vertex and does
                    // NOT open a drawer over the shape being drawn. The SVG's own
                    // `onPointerUp` still sees the gesture and adds the point.
                    if (zoneKeyboardDraft) return;
                    // β›” NO LONGER MERELY "a finished pan is not a click" (R10): a drag that ends
                    // on a pin would now OPEN a drawer, not just move the selection. See the
                    // `pinSelect` doc comment above before touching this line.
                    if (movedRef.current) return;
                    // ⭐ THE SPLIT R10 ASKS FOR, and `verify_map.py::structural_scan` reads it
                    // STRUCTURALLY: the select lives inside this block and the open lives outside
                    // it, which is the one claim a substring search cannot make.
                    const additive = e.shiftKey || e.ctrlKey || e.metaKey;
                    // Table selects on click. The default surface keeps its existing open gesture.
                    if (pinClickSelects) {
                      pinSelect(p.pid, additive);
                      return;
                    }
                    if (additive) {
                      pinSelect(p.pid, true);
                      return;
                    }
                    // β›”β›” R14 (W50-T14, 2026-09-03) β€” THERE IS NO `routePanelOpen` BRANCH HERE ANY
                    // MORE, AND ITS ABSENCE IS THE FIX. Until this date the block that stood at
                    // this exact spot read `if (routePanelOpen) { requestRoutePinMembership(...);
                    // return; }`, so with the Routes panel open EVERY pin on the map answered a
                    // plain click with an add-or-remove-stop prompt and `onOpen` below was
                    // unreachable. Worse, with the panel open and no route active the prompt could
                    // not even be raised: the user got the notice "Open a route first." and the
                    // record still never opened. That is the defect R14 names, verbatim:
                    // *"clicking a PIN on the map while a route is open does not open the record;
                    // stop rows are not the complaint."*
                    // β›” DO NOT REINSTATE IT ANYWHERE IN THIS HANDLER, and do not move it to a
                    // double click or to a new modifier: membership keeps its two VISIBLE doors,
                    // the "Add record" picker in the Route panel and the per-stop remove control
                    // on a stop row, both of which call the API directly from `RouteNav.tsx`. A
                    // pin is a record, and a click on a record opens it.
                    // Policed by `verify_map.py::RETIRED_ROUTE_PIN_GUARDS` and its Route-mode NCs.
                    // ⭐⭐ W41-T48 (owner instruction 22) β€” OPENING A RECORD FOLDS THE RAIL, ON
                    // THE MAP EXACTLY AS IN THE GRID. `CustomerGrid.tsx::onCellClicked` raises
                    // this on every cell click; the map was the one surface that opened a record
                    // and left the navigation at full width. Raised here and NOT beside the
                    // modifier branch above, because a shift-click works the selection and never
                    // opens anything.
                    // β›” `e.detail <= 1`, AND IT IS NOT A MICRO-OPTIMISATION. A double click on a
                    // pin fires `click` TWICE and then `dblclick`, and the `onDoubleClick` below
                    // re-opens the same pid ON PURPOSE (see its own note) -- so a bare `signal()`
                    // beside each `onOpen` would raise a PUBLIC contract event three times for
                    // ONE gesture. `detail` is the browser's own count of where a click sits in
                    // the gesture (1, then 2, and 2 again on `dblclick`), so the first click of
                    // any gesture signals and its repeats cannot. A time window would have been a
                    // guess at the OS double-click threshold; this is that threshold's own answer.
                    // ⚠ `<= 1` rather than `=== 1`: a synthetic `element.click()` carries
                    // `detail === 0`, and a programmatic open is still an open.
                    if (!routeApplication && e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
                    onOpen(p.pid);
                  }}
                  // ⚠ KEPT AFTER R10, AND IT IS NO LONGER AN ESCALATION. A plain click already
                  // opened the record, so this fires `onOpen` a second time on the SAME pid --
                  // idempotent, because the host's handler is a `setDetailPid` identity. It stays
                  // because removing it would make a double click on a pin do nothing at all,
                  // and because a user who learned the old gesture keeps getting the record.
                  // β›”β›” W41-T48 β€” AND THIS IS WHY IT RAISES NO `NAV_MINIMIZE_EVENT`. The absence
                  // is deliberate and is not an oversight for a later sweep to "fix": by the
                  // paragraph above, this handler is a REPEAT of an open the plain click already
                  // performed, on a pid the rail has already folded for. `onOpen` is idempotent
                  // and a duplicate event would be too (`Shell.tsx::onNavMinimize` is a bare
                  // `setNavCollapsed(true)`), but a public contract event that fires three times
                  // for one gesture is a lie to every listener added after this one.
                  // β›” R14 (2026-09-03) β€” the Route-mode early return that used to sit
                  // between the `preventDefault` and the open is gone with the pin-click
                  // membership shortcut it belonged to. It made a double click on a pin do
                  // NOTHING while the Routes panel was open; the paragraph above is the whole
                  // rationale for this handler and it does not have a Route-mode exception.
                  onDoubleClick={(e) => {
                    if (movedRef.current) return;
                    e.preventDefault();
                    // Table opens here. The default surface already opened on click.
                    if (pinClickSelects && !routeApplication) signal(NAV_MINIMIZE_EVENT);
                    onOpen(p.pid);
                  }}
                  onKeyDown={(e) => {
                    // ⚠ AFTER R10 THIS IS THE MIRROR, not the exception it used to be: Enter opens
                    // exactly as a plain click now does, and Space is the selection half exactly
                    // as a modifier click is. Space with a modifier toggles; Space alone still
                    // REPLACES the selection, which is the only surface left that can.
                    // β›” No `movedRef` check here, deliberately: a keypress has no drag to
                    // disambiguate, so the guard the pointer needs would only be superstition.
                    if (e.key === "Enter") {
                      e.preventDefault();
                      // β›” R14 (2026-09-03) β€” the Route-mode divert that stood here is retired with
                      // the pin-click one above. Enter is the plain click's MIRROR, so an
                      // exception on one and not the other is how a keyboard user and a pointer
                      // user come to disagree about what a pin does.
                      // W41-T48 β€” the keyboard mirror of the plain click, so it folds the rail
                      // for the same reason. ⚠ `!e.repeat` is this path's `e.detail <= 1`: a HELD
                      // Enter auto-repeats keydown for as long as the finger is down, and every
                      // one of those is the same gesture. The browser flags the repeats itself,
                      // so nothing here has to guess at a key-repeat rate either.
                      if (!routeApplication && !e.repeat) signal(NAV_MINIMIZE_EVENT);
                      onOpen(p.pid);
                      return;
                    }
                    if (e.key !== " ") return;
                    e.preventDefault();
                    pinSelect(p.pid, e.shiftKey || e.ctrlKey || e.metaKey);
                  }}
                >
                  <title>{p.title}</title>
                </circle>
              );
            })}
          </g>
          {/* I18 β€” the hover card. Wave 8 painted the title alone; a map whose
              pins carry a colour and a size encoding should say what they ARE.
              ⚠ Every value goes through `formatDisplay`, the SAME formatter the
              grid cells use, so a currency, a percentage or a date can never
              read one way on the map and another way in the table.
              Drawn in SVG screen space rather than as an HTML overlay: the
              viewBox letterboxes under preserveAspectRatio, so an HTML card
              would need the rendered scale re-derived, and this needs no
              conversion at all. pointer-events stay off β€” a card that can
              swallow the next click is a scar this codebase already carries. */}
          {/* Stop numbers, in SCREEN space so they stay legible at every zoom.
              pointer-events off: a badge sitting over a pin must not steal the
              click that opens the record β€” re-rooting the route is the "Start"
              picker's job, where it is visible and reversible. */}
          {plan &&
            plan.ordered.map((p, i) => {
              if (p.pid === DEPOT_PID) return null;
              const s = toScreen(p.p, view);
              return (
                <g
                  className="cg-map-stopno"
                  key={p.pid}
                  transform={`translate(${s.x.toFixed(2)} ${(s.y - 13).toFixed(2)})`}
                >
                  <circle r={7.5} />
                  <text textAnchor="middle" dy="3.4">{i + 1 - (plan.depot ? 1 : 0)}</text>
                </g>
              );
            })}
          {hovered && (() => {
            const s = toScreen(hovered.p, view);
            const lines: string[] = [];
            if (colorField)
              lines.push(`${colorField.label}: ${formatDisplay(colorField, hovered.colorVal) || "(blank)"}`);
            if (sizeField)
              lines.push(`${sizeField.label}: ${formatDisplay(sizeField, hovered.sizeVal) || "(blank)"}`);
            const title = hovered.title || "(untitled)";
            // Inter's average advance at 11.5px. An estimate, deliberately
            // generous: too wide is a slightly roomy card, too narrow is text
            // spilling past its own background.
            const w = Math.max(title.length, ...lines.map((l) => l.length)) * 6.2 + 20;
            const h = 21 + lines.length * 14;
            const b = cardBox(s.x, s.y, w, h, VIEW_W, VIEW_H);
            return (
              <g className="cg-map-card" aria-hidden="true">
                <rect x={b.x} y={b.y} width={w} height={h} rx={5} />
                <text className="cg-map-card-t" x={b.x + 10} y={b.y + 15}>{title}</text>
                {lines.map((l, i) => (
                  <text className="cg-map-card-l" key={i} x={b.x + 10} y={b.y + 15 + 14 * (i + 1)}>
                    {l}
                  </text>
                ))}
              </g>
            );
          })()}
          {rect && (
            <rect
              className="cg-map-marquee"
              x={rect.x0}
              y={rect.y0}
              width={rect.x1 - rect.x0}
              height={rect.y1 - rect.y0}
            />
          )}
          {/* The loop paints as a POLYGON, so the shape on screen is the shape
              the hit test uses β€” an open <polyline> would draw a mouth the
              selection does not have. Same class as the rectangle: one marquee
              look, and no new stylesheet rule (index.css is not this fence). */}
          {lassoPts && (
            <polygon
              className="cg-map-marquee"
              points={lassoPts.map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ")}
            />
          )}
          {/* β›”β›” W46-T17. THIS GROUP IS LAST ON PURPOSE, AND THAT IS THE WHOLE
              INVISIBLE-ZONE BUG. It used to sit directly under the water rect,
              ABOVE `<g transform={tf}>` in document order. SVG has no z-index:
              it paints in document order, so the opaque tile bed and every
              raster tile in that group painted straight OVER the draft. The
              draft was rendering correctly and being buried, which is why the
              vertex count went up while the screen showed nothing. Moved here,
              after the marquee, it is on top of everything.
              ⚠ It is still OUTSIDE the transform, exactly as before, because
              `cursor`, `points` and `center` are SCREEN coordinates; putting it
              inside `tf` would double-apply the camera. --- */}
          {zoneKeyboardDraft && (
            /* β›”β›” W47-T02 CAUSE 1, RENDER SITE 3 OF 4 - AND THE ONE A TWO-SITE SPEC MISSES.
                `beginEditZone` does `setZoneColor(zone.color)` RAW, so opening a colourless Zone
                for edit puts "" into `zoneColor` and every preview shape below painted black too.
                The ticket named two assemblies; the third is real, so it is fixed here rather
                than left for the next report. The draft lives OUTSIDE `tf`, so its clamp takes no
                zoom argument: these coordinates are already screen space. */
            <g className="cg-zone-keyboard-draft" aria-hidden="true">
              {zoneKeyboardDraft.shape === "polygon" && zoneKeyboardDraft.points.length > 0 && (
                <polyline
                  points={[...zoneKeyboardDraft.points, zoneKeyboardDraft.cursor]
                    .map((point) => `${point.x},${point.y}`).join(" ")}
                  fill="none" stroke={zonePaint(zoneColor)} strokeWidth="3" strokeDasharray="6 4"
                />
              )}
              {zoneKeyboardDraft.shape === "circle" && zoneKeyboardDraft.center && (
                <circle
                  cx={zoneKeyboardDraft.center.x} cy={zoneKeyboardDraft.center.y}
                  r={clampZoneRadius(Math.hypot(
                    zoneKeyboardDraft.cursor.x - zoneKeyboardDraft.center.x,
                    zoneKeyboardDraft.cursor.y - zoneKeyboardDraft.center.y
                  ))}
                  fill={zonePaint(zoneColor)} fillOpacity={zoneFillOpacity} stroke={zonePaint(zoneColor)}
                  strokeWidth="3" strokeDasharray="6 4"
                />
              )}
              {zoneKeyboardDraft.points.map((point, index) => (
                <circle key={`${point.x}:${point.y}:${index}`} cx={point.x} cy={point.y} r="4" fill={zonePaint(zoneColor)} />
              ))}
              <circle cx={zoneKeyboardDraft.cursor.x} cy={zoneKeyboardDraft.cursor.y} r="6" fill={zonePaint(zoneColor)} stroke="white" strokeWidth="2" />
            </g>
          )}
        </svg>

        {/* --- I18 β€” the camera controls. Zoom in / zoom out / fit to data, the
            affordance every map has, replacing wave 8's link-button-in-a-text-bar.
            OUTSIDE the <svg> deliberately: a mousedown on a button inside it would
            begin a pan. Icons are SVG strokes β€” no emoji, no glyph font. The zoom
            buttons DISABLE at the limits, which is also how the honesty cap on
            zoom-in makes itself visible instead of just feeling stuck.
            ⭐⭐ OWNER ITEM 1 (2026-08-23) β€” IT IS A NAVIGATION BAR NOW, AT THE TOP MIDDLE.
            Owner: *"the navigation for 'Zoom in (+)' etc. should not be at the top left of the
            Map. it should be at the top MIDDLE of the map, and horizontal. Make the icon bigger
            so its easier to see. Make it look like a proper navigation bar."* Centred, 34px keys
            with 20px glyphs, and two new ones: Rotate left and Rotate right, 5 degrees a click.
            ⚠ THE ROTATE PAIR BRACKETS THE CAMERA KEYS rather than sitting at one end. Turning
            left and turning right are one control with two directions; splitting them would
            leave a reader hunting for the second half of a pair. --- */}
        <div className="cg-map-ctl" role="group" aria-label="Map camera">
          <button
            type="button"
            className="cg-map-ctl-b"
            title={`Rotate left (${ROTATE_STEP} degrees per click, or press the [ key)`}
            aria-label="Rotate left"
            onClick={() => rotateBy(-ROTATE_STEP)}
          >
            {/* A dial arrow turning anticlockwise. The arrowhead is what says WHICH way, so it is
                drawn as a filled wedge rather than a stroked chevron: at 20px a two-line chevron
                on a curve reads as a kink in the curve. */}
            <svg viewBox="0 0 20 20" aria-hidden="true">
              <path d="M5.2 7.4A6 6 0 1 1 4 11" />
              <path className="cg-map-ctl-head" d="M2.4 4.2 6.2 8.1 2.1 8.6z" />
            </svg>
          </button>
          <button
            type="button"
            className="cg-map-ctl-b"
            // A greyed button with no reason reads as broken, not as honest β€”
            // and filtering to a single metro can push the FITTED zoom past the
            // cap, so this can be disabled the instant the view opens. Say why,
            // and point at the thing that does go further.
            // ⚠ W37-T35 REWROTE THIS SENTENCE because tiles made it false. It used to read
            // "the basemap's detail ends here; use Open in Google Maps for street level", which
            // was the honest thing to say about a vendored polygon and is simply untrue over a
            // street map. Which limit you have actually reached now depends on which basemap is
            // under you, so the copy says which.
            title={
              view.k >= kMax * (1 - 1e-9)
                ? tileLayer
                  ? "Zoom in. You are as far in as the map provider goes."
                  : "Zoom in. The offline basemap runs out here, so use Open in Google Maps for street level."
                : "Zoom in (+)"
            }
            aria-label="Zoom in"
            disabled={view.k >= kMax * (1 - 1e-9)}
            onClick={() => zoomBy(1.6)}
          >
            <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M8 3.6v8.8M3.6 8h8.8" /></svg>
          </button>
          <button
            type="button"
            className="cg-map-ctl-b"
            title="Zoom out (βˆ’)"
            aria-label="Zoom out"
            disabled={view.k <= kMin * (1 + 1e-9)}
            onClick={() => zoomBy(1 / 1.6)}
          >
            <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3.6 8h8.8" /></svg>
          </button>
          <button
            type="button"
            className="cg-map-ctl-b"
            // ⭐ ITEM 1 β€” THE TITLE EARNED A SECOND CLAUSE because the button gained a second
            // job: `fit` carries no bearing, so this is also the way back to north. A control
            // that silently un-rotates the map is a surprise; one that says it does is the undo.
            title="Fit to data and face north (0)"
            aria-label="Fit to data and face north"
            onClick={doFit}
          >
            <svg viewBox="0 0 16 16" aria-hidden="true">
              <path d="M2.6 5.8V2.6h3.2M10.2 2.6h3.2v3.2M13.4 10.2v3.2h-3.2M5.8 13.4H2.6v-3.2" />
              <path d="M6.6 8h2.8M8 6.6v2.8" />
            </svg>
          </button>
          {/* The selection SHAPE. Not a mode for selecting β€” shift-drag selects
              either way β€” so the note over `onPointerDown` still stands. The
              icon shows the shape you will get, which is the only "on" state
              available: `.cg-map-ctl-b` has no pressed style and index.css
              belongs to another session this wave, so a pressed look would have
              been a control that cannot show its own state. */}
          <button
            type="button"
            className="cg-map-ctl-b"
            title={
              lassoTool
                ? "Selection shape: lasso - shift-drag traces a freehand loop. Click for a rectangle."
                : "Selection shape: rectangle - shift-drag draws a box. Click for a freehand lasso."
            }
            aria-label="Selection shape"
            aria-pressed={lassoTool}
            onClick={() => setLassoTool((v) => !v)}
          >
            {lassoTool ? (
              <svg viewBox="0 0 16 16" aria-hidden="true">
                <path d="M12.1 6.2c1.1 1.6.3 3.5-1.9 4.4-2.4 1-5.5.5-6.7-1.1-1-1.4-.1-3.1 2-3.9 2.2-.8 4.9-.5 6.1.6" />
                <path d="M4.9 10.3 4.2 13.4" />
              </svg>
            ) : (
              <svg viewBox="0 0 16 16" aria-hidden="true">
                <path d="M3.2 4.4h9.6v7.2H3.2z" />
              </svg>
            )}
          </button>
          {/* The street-level hand-off, aimed at whatever is on screen right
              now. This is what makes the zoom cap honest rather than merely
              restrictive: the map stops where its geometry stops, and points at
              something that does not. */}
          <a
            className="cg-map-ctl-b"
            href={areaUrl}
            target="_blank"
            rel="noopener noreferrer"
            title="Open this area in Google Maps (new tab)"
            aria-label="Open this area in Google Maps"
          >
            <GoogleMapsMark />
          </a>
          <button
            type="button"
            className="cg-map-ctl-b"
            title={`Rotate right (${ROTATE_STEP} degrees per click, or press the ] key)`}
            aria-label="Rotate right"
            onClick={() => rotateBy(ROTATE_STEP)}
          >
            {/* The mirror of Rotate left, and drawn as its mirror rather than re-derived, so the
                two cannot end up subtly different weights on the same bar. */}
            <svg viewBox="0 0 20 20" aria-hidden="true">
              <path d="M14.8 7.4A6 6 0 1 0 16 11" />
              <path className="cg-map-ctl-head" d="M17.6 4.2 13.8 8.1 17.9 8.6z" />
            </svg>
          </button>
        </div>

        {/* --- W37-T35 β€” THE CREDIT LINE. β›” A LICENCE TERM, NOT DECORATION.
            OpenStreetMap's terms require visible attribution wherever its tiles appear, and every
            provider that could replace it says the same. Both the text and the link come from the
            server's provider config, so a swap carries its own credit and cannot leave the
            previous vendor's name on screen. It is rendered only while tiles are actually
            painting: crediting a provider whose tiles failed to load would be a false statement
            about what you are looking at. --- */}
        {tileLayer && tiles.attribution && (
          <div className="cg-map-credit">
            <a href={tiles.attributionUrl} target="_blank" rel="noopener noreferrer">
              {tiles.attribution}
            </a>
          </div>
        )}
        {/* --- legends (I3/I5). Floated over the map, never in the flow. --- */}
        {(colorBuckets || sizeLegend || (sizeField && sizeRange && sizeRange.min < 0)) && (
          <div className="cg-map-legends">
            {colorField && colorBuckets && (
              <div className="cg-map-legend">
                <div className="cg-map-legend-t">{colorField.label}</div>
                {colorBuckets.order.slice(0, SERIES.length + 1).map((k) => {
                  const c = k === "" ? OVERFLOW : colorBuckets.swatch.get(k) ?? OVERFLOW;
                  return (
                    <div key={k || "(blank)"} className="cg-map-legend-row">
                      <span
                        className="cg-map-swatch"
                        style={{ background: c.fill, borderColor: c.line }}
                      />
                      <span className="cg-map-legend-k">{k === "" ? "(blank)" : k}</span>
                      <span className="cg-map-legend-n">
                        {(colorBuckets.counts.get(k) ?? 0).toLocaleString()}
                      </span>
                    </div>
                  );
                })}
                {colorBuckets.overflow > 0 && (
                  <div className="cg-map-legend-note">
                    {colorBuckets.overflow.toLocaleString()} further value
                    {colorBuckets.overflow === 1 ? " is" : "s are"} drawn grey. The palette
                    holds {SERIES.length} colours, and reusing one would make two values look
                    like the same value.
                  </div>
                )}
              </div>
            )}
            {sizeField && sizeRange && (
              <div className="cg-map-legend">
                <div className="cg-map-legend-t">{sizeField.label}</div>
                {sizeLegend ? (
                  <div className="cg-map-sizerow">
                    {sizeLegend.map((v, i) => {
                      const r = bubbleRadius(v, sizeRange.min, sizeRange.max, R_MIN, R_MAX, R_NULL);
                      return (
                        <span key={i} className="cg-map-sizeitem">
                          <svg width={R_MAX * 2 + 2} height={R_MAX * 2 + 2} aria-hidden>
                            <circle
                              cx={R_MAX + 1}
                              cy={R_MAX + 1}
                              r={r}
                              fill={DEFAULT_PIN.fill}
                              stroke={DEFAULT_PIN.line}
                            />
                          </svg>
                          <span className="cg-map-legend-k">{formatDisplay(sizeField, v)}</span>
                        </span>
                      );
                    })}
                  </div>
                ) : (
                  <div className="cg-map-legend-note">
                    Every mapped record has the same {sizeField.label.toLowerCase()}, so the
                    bubbles cannot differ in size.
                  </div>
                )}
                {sizeRange.min < 0 && (
                  <>
                    <div className="cg-map-legend-row">
                      <span
                        className="cg-map-swatch"
                        style={{ background: LP_RED, borderColor: LP_RED_DEEP }}
                      />
                      <span className="cg-map-legend-k">Negative values</span>
                    </div>
                    <div className="cg-map-legend-note">
                      Size shows the value’s magnitude; values below zero are red.
                    </div>
                  </>
                )}
                {sizeRange.missing > 0 && (
                  <div className="cg-map-legend-note">
                    {sizeRange.missing.toLocaleString()} mapped record
                    {sizeRange.missing === 1 ? " has" : "s have"} no value, so they are drawn
                    at the smallest dot and never removed from the map.
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
        {/* ═══════════════════════════════════════════════════════════════════════════════════
            THE ROUTE PANEL β€” rebuilt for owner items 2, 4, 6, 8 and 9.

            ⭐⭐ ITEM 2 IS THE STRUCTURAL ONE AND IT IS WHY THIS IS ONE REBUILD RATHER THAN FIVE
            EDITS. The panel used to render its entire body inside `selectedPids.size >= 2`, so
            clicking Route with nothing chosen produced a box containing one sentence telling you
            off. The owner's answer: show the navigation, empty. So the chrome, the travel mode,
            the stop list and the record search are UNCONDITIONAL, and only the parts that
            genuinely describe a solved route (the distance, the visit numbers, the save target)
            wait for `plan`.

            β›” `plan` IS NULL UNTIL `routeOn` FLIPS **AND** TWO STOPS CAN BE ROUTED, so every read
            of `plan.*` below sits inside a `plan &&`. The old code was safe only because the whole
            body was behind the two-selected wall this item removes; `plan.ordered[0]` with nothing
            selected is a crash, not a blank.
            ═══════════════════════════════════════════════════════════════════════════════════ */}
        {mapNavigator === "routes" && (
          <aside id="cg-route-popover" className="cg-route-popover cg-route-nav-panel cg-route-index" aria-label="Routes">
            {navigatorTabs}
            <div className="cg-route-panel-scroll" role="region" aria-label="Route panel" tabIndex={0}>
            {/* D-599 / W46-T22 - `zones` is the vocabulary a Route's Zone selector offers. It
                is already loaded here to draw the map, so RouteNav gets a pass-through and
                never a second fetch of its own. */}
            <RouteNav
              applicationName={applicationName}
              applicationId={applicationId}
              routes={namedRoutes}
              routesLoaded={routesLoaded}
              routesLoadError={routesLoadError}
              onRetryRoutes={() => void loadNamedRoutes()}
              folders={routeFolders}
              selectedIds={selectedRouteIds}
              activeRouteId={activeRouteId}
              sources={routeSources}
              storageKey={tableKey}
              createdRoute={createdRoute}
              onCreatedDismiss={() => setCreatedRoute(null)}
              onToggle={(route) => void toggleNamedRoute(route)}
              onActiveRouteChange={setActiveRouteId}
              onOpenRecord={onOpen}
              stopLabels={routeStopLabels}
              stopCoords={routeStopCoords}
              roundTrip={roundTrip}
              onRoundTripChange={(value) => {
                if (value) setRouteEndPid(null);
                // A saved/manual order is an intentional route, but an endpoint change asks for
                // a fresh constrained solve.  Leaving it in place would make the dropdown move
                // without changing the painted or timed route.
                setRouteOrder(null);
                setRoundTrip(value);
              }}
              routeStartPid={routeStartPid}
              routeEndPid={routeEndPid}
              onRouteStartChange={(pid) => {
                setRouteOrder(null);
                setRouteStartPid(pid);
                if (pid === routeEndPid) setRouteEndPid(null);
              }}
              onRouteEndChange={(pid) => { setRouteOrder(null); setRouteEndPid(pid); }}
              onStopAdded={(updated, sourceApplicationId) => {
                if (!routingAlive.current || sourceApplicationId !== applicationId) return;
                setNamedRoutes((current) => current.map((item) => item.id === updated.id
                  ? { ...item, ...updated, folderId: item.folderId, navOrder: item.navOrder }
                  : item));
              }}
              onCreate={createNamedRoute}
              onMoveToOrder={moveNamedRouteStop}
              onUpdate={updateNamedRoute}
              onDuplicate={duplicateNamedRoute}
              onDelete={deleteNamedRoute}
              onShare={shareNamedRoute}
              onRouteMove={moveNamedRoute}
              onRouteReorder={reorderNamedRoutes}
              onFolderCreate={createNamedRouteFolder}
              onFolderUpdate={updateNamedRouteFolder}
              onFolderDelete={deleteNamedRouteFolder}
              onFolderReorder={reorderNamedRouteFolders}
              onCreateStart={() => setSaveTarget("")}
              mapLinks={activeRouteMaps.links}
              mapLinkRefusal={activeRouteMapsRefusal}
              deliveries={routeDeliveries}
              deliveryRecipients={routeDeliveryRecipients?.people ?? null}
              zones={zones || []}
              deliveryRecipientError={deliveryRecipientError}
              onReloadDeliveryRecipients={() => { void loadRouteDeliveryRecipients(); }}
              onSchedule={scheduleNamedRouteDelivery}
              onDeleteDelivery={deleteNamedRouteDelivery}
            />
            {routePinNotice && (
              <span className="cg-w44-route-warning" role="status">{routePinNotice}</span>
            )}
            {routeSelectionWarning && (
              <span className="cg-w44-route-warning" role="status">{routeSelectionWarning}</span>
            )}
            </div>
          </aside>
        )}
        {zoneChooserPanelOpen && (
          <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label="Zone chooser">
            {navigatorTabs}
            <div className="cg-route-panel-scroll" role="region" aria-label="Zone panel" tabIndex={0}>
            <div className="cg-route-popover-head">
              <button type="button" className="cg-route-index-back" onClick={closeZoneChooser}>Back</button>
              <span className="cg-views-title">Zones</span>
            </div>
            <div className="cg-map-zones" role="group" aria-label="Choose visible Zones">
              <div id="cg-map-zone-choices" className="cg-map-zone-choices" role="group" aria-label="Visible map Zones">
                {(zones || []).length === 0 ? (
                  <span className="cg-map-zone-empty">No Zones yet.</span>
                ) : (zones || []).map((zone) => (
                  <div className="cg-map-zone-option" key={zone.id}>
                    <label className="cg-map-zone-choice">
                      <input
                        type="checkbox"
                        checked={activeZoneIds.has(zone.id)}
                        disabled={!zone.visible}
                        onChange={(event) => toggleZone(zone, event.target.checked)}
                      />
                      <span className="cg-map-zone-swatch" style={{ backgroundColor: zone.color }} aria-hidden="true" />
                      <span>{zone.visible ? zone.name : `${zone.name} (hidden)`}</span>
                    </label>
                    <button type="button" className="cg-map-zone-edit"
                      disabled={normalizedCustomerZones && !zone.permission?.canEdit}
                      onClick={() => beginEditZone(zone)} aria-label={`Edit ${zone.name}`}>
                      Edit
                    </button>
                  </div>
                ))}
              </div>
              <button type="button" className="cg-btn cg-btn--primary" onClick={beginNewZone}>New Zone</button>
              {/* β›” W46-T28 β€” `zoneErr` USED TO RENDER IN THE EDITOR PANEL ONLY, and half the
                  things that set it happen with the editor closed: `persistZoneGeometry` fires
                  from a boundary drag and now from a vertex drag, both of which happen right
                  here on the map with this list open. A rejected reshape would have failed in
                  silence, the shape snapping back with no reason given. Standing rule 1: a
                  refusal is reported, never silently enforced. */}
              {zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
            </div>
            </div>
          </aside>
        )}
        {zoneEditorPanelOpen && (
          <aside id="cg-zone-popover" className="cg-route-popover cg-route-nav-panel cg-zone-nav" aria-label={zoneEditor ? `Edit ${zoneEditor.name}` : "Create Zone"}>
            {navigatorTabs}
            <div className="cg-route-panel-scroll" role="region" aria-label="Zone panel" tabIndex={0}>
            <div className="cg-route-popover-head">
              <button type="button" className="cg-route-index-back" onClick={closeZoneEditor}>Back to Zones</button>
              <span className="cg-views-title">{zoneEditor ? "Edit Zone" : "New Zone"}</span>
            </div>
            <div className="cg-map-zones cg-map-zone-editor">
              <label className="cg-map-zone-control">
                Zone name
                <input
                  className="cg-input"
                  value={zoneName}
                  maxLength={120}
                  aria-label="Zone name"
                  placeholder="Name this Zone"
                  onChange={(event) => setZoneName(event.target.value)}
                />
              </label>
              <fieldset className="cg-zone-shape-picker">
                <legend>Boundary</legend>
                <div role="group" aria-label="Zone boundary shape">
                  <button type="button" aria-pressed={zoneDrawShape === "polygon"}
                    onClick={() => setZoneDrawShape("polygon")}>Polygon</button>
                  <button type="button" aria-pressed={zoneDrawShape === "circle"}
                    onClick={() => setZoneDrawShape("circle")}>Circle</button>
                </div>
                <span>Choose a shape, then drag on the map, or draw it by clicking.</span>
                {!zoneKeyboardDraft ? (
                  <button type="button" className="cg-link-btn cg-zone-draw-btn" onClick={startKeyboardZoneDrawing}>
                    <DrawZoneIcon />
                    Draw by clicking
                  </button>
                ) : (
                  <>
                    {/* β›”β›” W46-T28 β€” "FINISH SHAPE" IS THE MISSING CONTROL, not a convenience.
                        Pressing Enter only commits the outline while the MAP holds focus, and
                        naming the Zone moves focus into the input beside this. Without a button
                        in the panel, the only ending on offer was "Stop drawing", which throws
                        the points away, so a drawn shape could never reach the Save button. */}
                    <div className="cg-zone-draw-actions">
                      <button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
                        onClick={() => { finishZoneDraft(); }}>
                        <DrawZoneIcon />
                        Finish shape
                      </button>
                      <button type="button" className="cg-link-btn cg-zone-draw-btn"
                        onClick={() => { setZoneKeyboardDraft(null); setZoneErr(null); }}>
                        Stop drawing
                      </button>
                    </div>
                    <span role="status" aria-live="polite">
                      {zoneKeyboardDraft.shape === "polygon"
                        ? `${zoneKeyboardDraft.points.length} ${zoneKeyboardDraft.points.length === 1 ? "vertex" : "vertices"}. Click the map to add one, then choose Finish shape, or press Enter on the map.`
                        : zoneKeyboardDraft.center
                          ? "Center placed. Click its edge, then choose Finish shape."
                          : "Click the map to place the circle center, then click its edge."}
                    </span>
                  </>
                )}
              </fieldset>
              {/* ⭐⭐ W47-T03, RULING R4 β€” THE FINISHED SHAPE CARRIES ITS OWN TWO ENDINGS.
                  Before this there was no such thing as a finished-but-unsaved Zone on screen:
                  "Finish shape" cleared the only painted state and the user was left holding a
                  boundary they could not see, in front of a primary button that gave no sign it
                  now had something to save. The pair sits exactly where Finish shape / Stop
                  drawing were, because it is the same flow one step later.
                  β›” SAVE GOES THROUGH `saveZone`, NOT A SECOND WRITE PATH. `saveZone` already
                  reads `drawnZoneGeometry`, already states its own refusal in `zoneErr` when the
                  name is missing, and already clears the geometry on success so this row and the
                  dashed shape retire together the moment the solid saved Zone appears.
                  ⚠ Discard clears the geometry ONLY. It does not close the editor or reset the
                  name and colour: throwing away a boundary the user disliked should not also
                  throw away the two fields they typed before drawing it. */}
              {!zoneKeyboardDraft && drawnZoneGeometry && (
                <>
                  <div className="cg-zone-draw-actions cg-zone-unsaved-actions">
                    <button type="button" className="cg-link-btn cg-zone-draw-btn is-armed"
                      disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
                      onClick={() => { void saveZone(zoneEditor || undefined); }}>
                      Save zone
                    </button>
                    <button type="button" className="cg-link-btn cg-zone-draw-btn"
                      onClick={() => { setDrawnZoneGeometry(null); setZoneErr(null); }}>
                      Discard
                    </button>
                  </div>
                  <span className="cg-zone-unsaved-note" role="status" aria-live="polite">
                    Shape finished. It is not saved yet, and shows as the dashed outline on the
                    map until you choose Save zone.
                  </span>
                </>
              )}
              {zoneEditor && (
                <button
                  type="button"
                  className="cg-btn"
                  disabled={zoneBusy || (normalizedCustomerZones && !zoneEditor.permission?.canEdit)}
                  onClick={() => void setZoneVisible(zoneEditor, !zoneEditor.visible)}
                >
                  {zoneEditor.visible ? "Hide Zone" : "Show Zone"}
                </button>
              )}
              <label className="cg-map-zone-control">
                Color
                <select className="cg-route-select" value={zoneColor} aria-label="Zone color" onChange={(event) => setZoneColor(event.target.value)}>
                  {ZONE_COLOR_CHOICES.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}
                </select>
              </label>
              {/* ⭐ OWNER 2026-08-31 - the opacity is a dial now, not a constant. It sits beside
                  Color because both are how a Zone READS rather than what it covers, and it takes
                  effect on every Zone the moment it moves: the value is the custom property the
                  saved-Zone rule already consumes.
                  ⚠ The reading is shown as a PERCENTAGE because that is the unit the instruction
                  was given in ("80% opacity"), while the stored value stays the 0-1 fraction every
                  consumer expects - the conversion happens at this boundary and nowhere else. */}
              <label className="cg-map-zone-control">
                Fill opacity
                <input
                  type="range"
                  className="cg-zone-opacity-range"
                  min={0}
                  max={100}
                  step={5}
                  value={Math.round(zoneFillOpacity * 100)}
                  aria-label="Zone fill opacity"
                  aria-valuetext={`${Math.round(zoneFillOpacity * 100)} percent`}
                  onChange={(event) => setZoneFillOpacity(Number(event.currentTarget.value) / 100)}
                />
                <span className="cg-zone-opacity-read">{Math.round(zoneFillOpacity * 100)}%</span>
              </label>
              {/* β›”β›” W46-T28 β€” A MISSING NAME OR BOUNDARY NO LONGER DISABLES THIS BUTTON, and
                  that is the point rather than a loosening. A disabled control cannot say why it
                  is disabled, so the owner's "it won't even let me save" arrived with no reason
                  on screen at all. `saveZone` already has the message for both cases ("Name a
                  Zone and draw its boundary on the map.") and `zoneErr` renders at the foot of
                  this panel, so letting the click through turns a silent refusal into a stated
                  one. Permission and in-flight state still disable it: those are not the user's
                  mistake to correct. */}
              <button
                type="button"
                className="cg-btn cg-btn--primary"
                disabled={zoneBusy || (normalizedCustomerZones && !!zoneEditor && !zoneEditor.permission?.canEdit)}
                onClick={() => {
                  // An outline still being drawn is committed first, and its geometry handed
                  // straight down: state set in this tick is not readable from `saveZone`.
                  if (zoneKeyboardDraft) {
                    const pending = finishZoneDraft();
                    // `finishZoneDraft` has already put the real reason in `zoneErr`. Falling
                    // through would overwrite it with a vaguer one.
                    if (!pending) return;
                    void saveZone(zoneEditor || undefined, pending);
                    return;
                  }
                  void saveZone(zoneEditor || undefined);
                }}
                title={drawnZoneGeometry || zoneKeyboardDraft
                  ? (zoneEditor ? "Replace this Zone boundary with the drawn shape" : "Save the drawn Zone")
                  : zoneEditor ? "Save Zone details" : "Draw a boundary first"}
              >
                {zoneEditor ? "Update Zone" : "Save Zone"}
              </button>
              {zoneEditor && (!normalizedCustomerZones || zoneEditor.permission?.canDelete) && (
                <button type="button" className="cg-btn cg-btn--danger" disabled={zoneBusy}
                  onClick={() => setPendingZoneDelete(zoneEditor)}>
                  Delete Zone
                </button>
              )}
              {zoneErr && <span className="cg-cal-nodate" role="status">{zoneErr}</span>}
            </div>
            </div>
          </aside>
        )}
        {routeApplication && <RouteCustomerPane detail={customerDetail}
          onBack={() => onCustomerBack?.()} />}
      </div>
      {/* ═══════ W51-T28 / R6 β€” EVERY CONFIRM THIS SURFACE ASKS FOR, IN ONE PLACE ═══════════
          β›” MOUNTED AT THE COMPONENT ROOT, NOT BESIDE THE CONTROL THAT OPENS IT. Two of these
          were `window.confirm` calls inside a panel, and one lived inside the routes popover's
          own subtree. A dialog rendered inside a subtree that closes itself in the same handler
          unmounts before it paints, and the person sees nothing at all.
          β›” NO Z-INDEX IS SET HERE AND NONE IS NEEDED, AND W51-T32 MADE THAT MORE TRUE RATHER
          THAN LESS. The three navigator panels are now ordinary items in the map row, painting in
          the flow at the browser's default stacking; only the transient selection notice still
          floats at `--cg-z-mapchrome` (65). `ConfirmDialog` portals to <body> at `--cg-z-overlay`
          (110), so dialog over panel over pins still holds on the scale in `index.css :root`, and
          "raising" the dialog would be re-breaking the three-way order by hand. */}
      <ConfirmDialog
        open={pendingZoneDelete !== null}
        title={`Delete ${pendingZoneDelete?.name ?? "Zone"}?`}
        /* ⭐ A REAL COUNT, NOT A ROUNDED REASSURANCE (standing rules 1 and 8). `memberships` is
           the Zone's member pids and is already on the object the chooser drew, so the sentence
           states what deleting the shape actually leaves behind. */
        body={(() => {
          const kept = (pendingZoneDelete?.memberships || []).length;
          return kept === 1
            ? "1 stop keeps its records; the zone shape is removed"
            : `${kept.toLocaleString()} stops keep their records; the zone shape is removed`;
        })()}
        confirmLabel="Delete zone"
        tone="destructive"
        busy={zoneBusy}
        /* β›”β›” CLEARED ON SETTLE, NOT BEFORE THE DISPATCH, AND THE ORDER IS THE WHOLE POINT OF
           `busy`. Clearing first closes the dialog in the same batched render, so `open` is
           already false by the time `zoneBusy` flips and the locked buttons never paint: a prop
           that cannot render, with a gate needle pinning it, is precisely the shape this file's
           other legs exist to refuse. Re-entrancy is covered by `busy` disabling both buttons and
           by `ConfirmDialog` refusing to dismiss while busy, so nothing is lost by waiting. */
        onConfirm={() => {
          const zone = pendingZoneDelete;
          if (!zone || zoneBusy) return;
          void deleteZone(zone).finally(() => setPendingZoneDelete(null));
        }}
        onCancel={() => setPendingZoneDelete(null)}
      />
      <ConfirmDialog
        open={pendingRouteInclude !== null}
        /* ⚠ A SHORT NOUN PHRASE, per the kit's own contract and DESIGN.md section 2: the
           question lives in the body, and the button names the act. The zone delete ABOVE is
           the ONE title written as a question, because its exact wording is the done-when. */
        title="Route outside this filter"
        body={`${pendingRouteInclude?.name ?? "This route"} is outside this filter. Only this route's managed membership group is included.`}
        confirmLabel="Include route"
        tone="primary"
        onConfirm={confirmPendingRouteInclude}
        onCancel={() => setPendingRouteInclude(null)}
      />
      {/* ⚠ UNREACHABLE TODAY, AND CONVERTED ANYWAY. R14 (W50-T14) retired the pin click and the
          pin Enter, which were `requestRoutePinMembership`'s only two callers, so nothing sets
          `routePinPrompt` at present. The machinery is deliberately kept whole and wired
          (verify_map.py's `single-stop-door` / `actual-membership` / `visible-confirmation` legs
          all still hold it), so leaving the one native-shaped prompt behind would have left R6
          half-applied for whoever reinstates a door. */}
      <ConfirmDialog
        open={routePinPrompt !== null}
        title={routePinPrompt?.present ? "Add a route stop" : "Remove a route stop"}
        body={routePinPrompt
          ? `${routePinPrompt.title} will be ${routePinPrompt.present ? "added to" : "removed from"} ${activeNamedRoute?.name || "this Route"}.`
          : undefined}
        confirmLabel={routePinPrompt?.present ? "Add stop" : "Remove stop"}
        tone={routePinPrompt?.present ? "primary" : "destructive"}
        busy={routePinBusy}
        onConfirm={() => void confirmRoutePinMembership()}
        onCancel={() => setRoutePinPrompt(null)}
      />
    </div>
  );
}

export type MapViewProps = Omit<Parameters<typeof MapViewSurface>[0], "field" | "onOpen" | "pinClickSelects"> & {
  field?: Field; fields?: Field[];
  onOpen: (pid: number, row?: Row) => void;
  routingFilterNodes?: FilterNode[];
  routingFilterConj?: Conjunction;
  onCatalogData?: (fields: Field[], rows: Row[]) => void;
};

interface RegistryTemplateApplication {
  id: string;
  name: string;
  type: string;
  templateKind?: unknown;
  sourceDatabase?: unknown;
  fieldMap?: unknown;
  openTarget?: { database?: unknown };
  compatibleDatabases?: unknown[];
  config?: { schemaVersion: 1; display: Record<string, unknown> };
  revision?: number;
  capabilities?: { edit?: boolean };
}

type TemplateApplicationState =
  | { phase: "idle" }
  | { phase: "loading"; key: string }
  | { phase: "ready"; key: string; application: RegistryTemplateApplication | null }
  | { phase: "error"; key: string; message: string };

/** Resolve an Application deep link from the registry before selecting a specialized renderer.
 * CustomerGrid still applies the definition's ordinary display config; this wrapper only handles
 * the route and catalog discriminators which deliberately share the trusted Map mode. */
export function MapView(props: MapViewProps) {
  // C3: a hosted map reads no hash. Its database is the grid's own, and an address names no Application.
  const hosted = props.hosted === true;
  const target = hosted ? undefined : readDataPath();
  const applicationId = target?.application ?? "";
  const database = hosted ? props.tableKey : target?.database ?? "";
  const requestKey = applicationId && database ? `${database}::${applicationId}` : "";
  const [state, setState] = useState<TemplateApplicationState>(() => requestKey
    ? { phase: "loading", key: requestKey }
    : { phase: "idle" });
  const requestGeneration = useRef(0);
  const applicationRef = useRef<RegistryTemplateApplication | null>(null);
  const catalogSaveQueue = useRef<Promise<void>>(Promise.resolve());

  useEffect(() => {
    const mine = ++requestGeneration.current;
    applicationRef.current = null;
    if (!applicationId || !database) {
      setState({ phase: "idle" });
      return;
    }
    const controller = new AbortController();
    setState({ phase: "loading", key: requestKey });
    void fetch(`${API_V1}/applications?database=${encodeURIComponent(database)}`, {
      credentials: CREDENTIALS,
      signal: controller.signal,
    }).then(async (response) => {
      const body = await response.json().catch(() => ({}));
      if (!response.ok) {
        throw new Error(String(
          body?.detail?.message ?? body?.detail ?? "The Application could not be loaded.",
        ));
      }
      const applications = Array.isArray(body?.applications)
        ? body.applications as RegistryTemplateApplication[]
        : [];
      const application = applications.find((candidate) => candidate.id === applicationId) ?? null;
      if (!application) throw new Error("This Application is no longer available.");
      const compatible = application.openTarget?.database === database ||
        application.compatibleDatabases?.includes(database) === true;
      if (!compatible) throw new Error("This Application cannot open this database.");
      if (controller.signal.aborted || mine !== requestGeneration.current) return;
      const live = hosted ? undefined : readDataPath();
      if (!hosted && (live?.application !== applicationId || live?.database !== database)) return;
      applicationRef.current = application;
      setState({ phase: "ready", key: requestKey, application });
    }).catch((error: unknown) => {
      if (controller.signal.aborted || mine !== requestGeneration.current) return;
      setState({
        phase: "error",
        key: requestKey,
        message: error instanceof Error ? error.message : "The Application could not be loaded.",
      });
    });
    return () => controller.abort();
  }, [applicationId, database, requestKey, hosted]);

  if (applicationId && (state.phase === "idle" || state.key !== requestKey || state.phase === "loading")) {
    return (
      <LogoLoader className="cg-app-launch-state" />
    );
  }
  if (applicationId && state.phase === "error" && state.key === requestKey) {
    return <div className="cg-app-launch-state is-error" role="alert">{state.message}</div>;
  }

  const application = state.phase === "ready" && state.key === requestKey ? state.application : null;
  const surface = applicationTemplateSurface(application);
  // R33: the registry serves a Routing or Catalog App with its C1 Odoo binding as `fieldMap`.
  const fieldMap = application?.fieldMap && typeof application.fieldMap === "object" &&
    !Array.isArray(application.fieldMap)
    ? application.fieldMap as Record<string, unknown>
    : {};

  if (surface === "catalog") {
    const key = String(fieldMap.key ?? "");
    const title = String(fieldMap.title ?? "");
    if (!application || !key || !title) {
      return <div className="cg-app-launch-state is-error" role="alert">The Catalog could not read its product fields.</div>;
    }
    const definition: CatalogApplicationDefinition = {
      id: application.id,
      name: application.name,
      templateKind: "catalog",
      sourceDatabase: String(application.sourceDatabase ?? database),
      fieldMap: {
        key,
        title,
        ...(fieldMap.image ? { image: String(fieldMap.image) } : {}),
        ...(fieldMap.sku ? { sku: String(fieldMap.sku) } : {}),
        ...(fieldMap.price ? { price: String(fieldMap.price) } : {}),
        ...(fieldMap.category ? { category: String(fieldMap.category) } : {}),
        ...(fieldMap.description ? { description: String(fieldMap.description) } : {}),
      },
    };
    const display = application.config?.display ?? {};
    const catalogs = Array.isArray(display.catalogs) ? display.catalogs as CatalogSpec[] : [];
    const catalogSpec = display.catalog && typeof display.catalog === "object" &&
      !Array.isArray(display.catalog)
      ? display.catalog as CatalogViewSpec
      : { titleField: title, imageField: definition.fieldMap.image };

    const onSave = (nextCatalogs: CatalogSpec[], nextSpec: CatalogViewSpec): Promise<void> => {
      const generation = requestGeneration.current;
      // Serialize saves, including after a refusal. Each edit sends the complete local draft,
      // and builds on the most recent server config instead of an earlier render's closure.
      const save = catalogSaveQueue.current.then(async () => {
        const current = applicationRef.current;
        if (generation !== requestGeneration.current || current?.id !== application.id) {
          throw new Error("This Application is no longer available.");
        }
        if (current.capabilities?.edit !== true) {
          throw new Error("You cannot edit this Application.");
        }
        const response = await fetch(`${API_V1}/applications/${encodeURIComponent(current.id)}`, {
          method: "PATCH",
          credentials: CREDENTIALS,
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            config: {
              schemaVersion: 1,
              display: {
                ...current.config?.display,
                mode: "map",
                catalogs: nextCatalogs,
                catalog: nextSpec,
              },
            },
          }),
        });
        const body = await response.json().catch(() => ({}));
        if (!response.ok) {
          // X2: every refusal is `{error: {code, message}}`; show the server's sentence.
          throw new Error(String(body?.error?.message ?? body?.detail?.message ??
            "The Catalog could not be saved."));
        }
        const updated = body?.application as RegistryTemplateApplication | undefined;
        if (!updated || updated.id !== current.id || !updated.config ||
            typeof updated.revision !== "number") {
          throw new Error("The Catalog save could not be confirmed.");
        }
        if (generation !== requestGeneration.current) return;
        applicationRef.current = updated;
        setState((live) => live.phase === "ready" && live.key === requestKey
          ? { ...live, application: updated }
          : live);
      });
      catalogSaveQueue.current = save.catch(() => {});
      return save;
    };

    return <div className="cg-app-frame-catalog"><AppFrame appName={application.name}
      actions={<AppFrameMarks mark="catalog" connector="odoo" />}>
      <CatalogApp definition={definition}
      key={`${requestKey}::${requestGeneration.current}`}
      database={database}
      scope={{
        filters: props.activeView?.config.filters ?? [],
        filterConj: props.activeView?.config.filterConj ?? "and",
        sorts: props.activeView?.config.sorts ?? [],
      }}
      onOpen={props.onOpen}
      onData={props.onCatalogData}
      editor={{
        catalogs,
        catalogSpec,
        canEdit: application.capabilities?.edit === true,
        onSave,
      }}
      />
    </AppFrame></div>;
  }

  if (surface === "route" && application) {
    const titleKey = String(fieldMap.title ?? "");
    const latitudeKey = String(fieldMap.latitude ?? "");
    const longitudeKey = String(fieldMap.longitude ?? "");
    const addressKey = String(fieldMap.address ?? "");
    const routeField: Field = props.field ?? { key: titleKey, label: "Record title", type: "text", source: "odoo" };
    const coordinateFields = latitudeKey && longitudeKey
      ? {
          latitude: { ...routeField, key: latitudeKey, label: "Latitude" },
          longitude: { ...routeField, key: longitudeKey, label: "Longitude" },
        }
      : props.coordinateFields;
    // The general geocoder reads its address contract from coordField. An empty key carries that
    // contract without pretending an address-only Application owns a coordinate column.
    const routeCoordField = addressKey
      ? {
          ...(props.coordField ?? routeField),
          key: props.coordField?.key ?? "",
          label: props.coordField?.label ?? "Route location",
          geocode: {
            addressField: addressKey,
            ...(props.coordField?.geocode?.country
              ? { country: props.coordField.geocode.country }
              : {}),
          },
        }
      : props.coordField;
    return (
      <RouteApplicationMapView
        key={application.id}
        titleKey={titleKey || routeField.key}
        applicationId={application.id}
        props={{
          ...props,
          field: titleKey ? { ...routeField, key: titleKey, label: "Record title" } : routeField,
          coordinateFields,
          coordField: routeCoordField,
          applicationName: application.name,
          geocodeSessionOnly: Boolean(addressKey),
          routeApplication: true,
        }}
        Surface={MapViewSurface}
      />
    );
  }

  if (!props.field) {
    return <div className="cg-app-launch-state is-error" role="alert">The Map key field is unavailable.</div>;
  }

  return <MapViewSurface {...props} field={props.field} pinClickSelects />;
}