File size: 163,903 Bytes
20bf676
 
 
 
 
 
 
 
 
dcdb685
20bf676
 
 
 
 
 
dcdb685
20bf676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
20bf676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
20bf676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
20bf676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20bf676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcdb685
 
 
 
 
 
 
 
 
 
 
 
 
20bf676
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useMemo, useRef, useState } from "react";
import { AnchoredOverlay } from "./OverlaySurface";
import type { AnchorRect } from "./OverlaySurface";
import { FieldTypeIcon, MenuLabel } from "./icons";
import { FieldSelectButton } from "./FieldSelect";
import { CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRenames,
  codeLanguageOf, directionLabel, isDerivedLink, isMachineOwned,
  isProfileField, parseOptions, ratingMax, ROLLUP_FN_LABELS, ROLLUP_FNS,
  ROLLUP_REF_OPS } from "./types";
import type { AggName, Field, FieldFormat, FieldScope, FieldType, Measure, RollupCondition, RollupFn,
  RollupRefOp, RollupSource, Viewer } from "./types";
import type { LinkTarget, RollupSourceOffer } from "./apiBridge";
import type { WindowSpec } from "./windows";
import { normalizeWindow, windowLabel } from "./windows";
import { WindowPicker } from "../filter-kit";
import { TYPE_LABELS } from "./iconShapes";
import { AGG_LABELS, aggOptions } from "./aggregations";
import { validateFormula } from "./formulaEngine";
import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
  OPTION_PALETTE } from "./choiceColors";

export interface ColumnMenuState {
  fieldKey: string;
  anchor: AnchorRect;
  /**

   * Item 12 (R8) β€” which pane this opening lands on. Absent = the action list, i.e. every

   * pre-wave-26 opening. `"edit"` is the kanban's "Add option" door.

   *

   * ⚠ Narrowed to the ONE pane that has a door rather than the whole `MenuPane` union: widening

   * it would let any future caller deep-link into `permissions`, whose entry is gated on the

   * viewer inside the menu's own action list β€” a state you can only reach through a check would

   * become a state you can reach around it.

   */
  pane?: "edit";
}

interface FieldConfigExtra {
  formula?: string;
  max?: number;
  scope?: FieldScope;
  label?: string;
  colorCodeOptions?: boolean;
  optionColors?: Record<string, string>;
  /**

   * ⭐ Wave-20 owner item 15 (contract C-RENAME) β€” **AN EXPLICIT MAPPING, NEVER A DIFF.**

   *

   * Renaming a choice used to change the DECLARED list and nothing else, so every cell still

   * held the old label and the column went blank-looking: "Blue" was no longer a choice, and

   * the rows that said "Blue" said something the field did not offer. The migration needs to

   * know that Blue BECAME Navy β€” and neither end can infer that from two lists, because

   * "renamed Blue to Navy" and "deleted Blue, added Navy" produce the identical pair

   * (`routes_tables.py` says the same thing from the server's side).

   *

   * It is knowable HERE, and only here: every option row carries a stable `OptionDraft.id`

   * from the moment the editor opens, so a row whose label changed is a RENAME by identity, a

   * new row is an addition, and a removed row is a removal. No guessing, at either end.

   */
  renames?: { from: string; to: string }[];
  /** Wave-18 C5-AUTOFIELD β€” an automation column's configuration, the same way `formula`

   *  carries an expression. Validated host-side (`aios_grid._clean_automation`). */
  automation?: { kind: string; source: "record_url_field" | "self"; urlField?: string };
  /** ⭐ 2026-08-07 β€” a `link` column's target. REQUIRED for the type: `_clean_field` returns

   *  None for a link with no bag, so a create without this is a column that never appears. */
  link?: { table: string; single?: boolean };
  /** ⭐ 2026-08-07 β€” a `rollup` column's aggregate. Same requirement, same reason.

   *  ⭐ 2026-08-09 β€” or, INSTEAD, a `source` binding: the read-through kind, which summarises

   *  rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`

   *  first and returns before it ever looks at `link`, so the two are exclusive by construction

   *  rather than by a rule someone has to remember. */
  rollup?: {
    link?: string; field?: string; fn?: string;
    limit?: number; sortBy?: string; sortDir?: "asc" | "desc";
    distinctBy?: string;
    /** ⭐⭐ 2026-08-09 β€” the PRE-filter: applied before the most-recent window, so "the last 10"

     *  counts only records that already match. `_clean_rollup` refuses a `ref` leaf here (there

     *  is no fixed set yet for a statistic to describe). */
    where?: RollupCondition[];
    whereConj?: "and" | "or";
    conditions?: RollupCondition[];
    conditionConj?: "and" | "or";
    source?: RollupSource;
  };
  /** ⭐ Wave-27 item 13 (R13) β€” a `code` column's language. OPTIONAL, unlike the two bags above

   *  it: `_clean_field` accepts a code column without one and it renders as plain text, so this

   *  is an ordinary edit rather than a create requirement. */
  code?: { language: string };
}

interface ColumnMenuProps {
  state: ColumnMenuState;
  field: Field;
  /** Every field of the table, for "Change field" (owner item 9): the clicked column can be

   *  swapped for any other field β€” including hidden ones like Notes β€” in place. */
  fields: Field[];
  /**

   * ⭐ 2026-08-07 β€” the OTHER databases a `link` column may point at, with their fields (so the

   * rollup editor can offer real column names rather than a free-text key). Supplied by the host

   * from `GET /tables`, which already filters by `may_open`.

   *

   * ⚠ ABSENT on the Odoo-backed Customer/Product grids, and that is what withdraws the two

   * relational types from their create menu β€” there is no second user table to point at there,

   * so offering "Link to another record" would be offering a column that can never resolve.

   */
  linkTargets?: LinkTarget[];
  /**

   * ⭐⭐ 2026-08-09 β€” the READ-THROUGH rollup's offer (topic β†’ measure β†’ dim β†’ window), fetched

   * by the host from `GET /tables/rollup-sources`.

   *

   * ⚠ EMPTY IS MEANINGFUL AND IS THE COMMON CASE. A tenant with no connected source gets `[]`,

   * and the editor then never renders the mode switch at all β€” a rollup is simply a link fold,

   * as it was before this existed. So this prop is what turns the second kind ON, not a flag.

   */
  rollupSourceOffer?: RollupSourceOffer;
  locked: boolean;
  /** Product-owned preset fields may still drive view actions, but their schema is immutable. */
  schemaLocked?: boolean;
  /** Wave-5 item 1 β€” who is looking. Gates the permissions entry (creator-or-admin). */
  viewer?: Viewer;
  /** Wave-5 item 3 β€” what the CURRENT VIEW does with this field, so the conditional

   *  "Don't sort/filter/group by this field" entries render exactly when they apply. */
  sortedDir: "asc" | "desc" | null;
  isFiltered: boolean;
  isGrouped: boolean;
  /** types.isGroupableField, computed by the caller (it owns lockedKey). */
  groupable: boolean;
  onClose: () => void;
  onNote: (note: string) => void;
  onHide: () => void;
  onCreate: (

    label: string,

    type: FieldType,

    anchorKey: string | null,

    side: "left" | "right" | "end",

    options?: string[],

    measureSpec?: { key: string; window: WindowSpec },

    extra?: FieldConfigExtra

  ) => void;
  /** Swap THIS column for another field, in place (owner item 9). */
  onChangeField: (newKey: string) => void;
  /**

   * Wave-2 item 5: the Change-field window's "New field" half β€” create a fresh overlay field

   * of the chosen type and swap this column for it in one motion. The old field hides exactly

   * as an ordinary change does. Wave-6 item 2 REPLACES this flow on created (`custom_`)

   * fields with `onRetype` below.

   */
  onCreateAndSwap: (

    label: string,

    type: FieldType,

    options?: string[],

    extra?: FieldConfigExtra

  ) => void;
  /**

   * Wave-6 item 2, re-homed by owner item 8 (2026-07-31): supplied for CREATED (`custom_`)

   * fields only β€” the EDIT FIELD pane's type picker RETYPES THIS FIELD IN PLACE (same key,

   * new type/options; values never converted β€” unreadable cells show blank, disclosed in the

   * pane). `extra.label` rides along when the name changed in the same save, so rename+retype

   * is ONE upsert β€” two sequential emits would each read the stale def and revert the other.

   */
  /** ⭐ 2026-08-07 (D-79) β€” flip the C3 profile flag on a `text` column of a `ut_*` table.

   *  Absent on every surface that is not a user table, which is what hides the control. */
  onProfileFlag?: (key: string, on: boolean) => void;
  onRetype?: (

    type: FieldType,

    options?: string[],

    extra?: FieldConfigExtra

  ) => void;
  /**

   * ⭐⭐ 2026-08-09 (owner) β€” RECONFIGURE an existing `link`/`rollup` column's bag.

   *

   * A DIFFERENT DOOR FROM `onRetype`, not a variant of it. `onRetype` writes the per-user overlay

   * stratum and refuses anything that is not a `custom_` overlay field; these bags live in the

   * table's SHARED definition and reach it through `PATCH /tables/{key}/fields/{fkey}`. Wiring

   * this through `onRetype` would have meant a Save button that runs and does nothing on exactly

   * the columns the owner was trying to edit.

   *

   * ⚠ Supplied for USER DATABASES only β€” its absence is what withdraws the editor from the

   * Odoo-backed grids, where there is no such endpoint.

   */
  onFieldConfig?: (patch: {

    label?: string;

    link?: Record<string, unknown>;

    rollup?: Record<string, unknown>;

  }) => void;
  /** Wave-6 item 5 β€” rename this created field (ordinary field_upsert with a new label).

   *  Supplied for creatable strata only. */
  onRename?: (label: string) => void;
  /**

   * Owner item 8 (2026-07-31) β€” edit a FORMULA field's source in place (the Edit-field pane's

   * per-type editor for the formula type, validated with the field itself as selfKey so a

   * cycle is refused at authoring). `label` rides along exactly like onRetype's β€” one upsert.

   * Supplied for created formula fields only.

   */
  onFormula?: (formula: string, label?: string) => void;
  /** Wave-6 item 4 β€” open straight into the create form at this position (the header "+"

   *  passes "end"). Cancel then CLOSES rather than falling back to the action list. */
  initialPosition?: CreatePosition;
  /**

   * ⭐ WAVE-26 ITEM 12 (owner ruling R8) β€” open straight into a PANE, the way `initialPosition`

   * opens straight into the create form.

   *

   * The kanban's "Add option" door passes `"edit"`. The owner's words were *"its literally the

   * same thing as adding a new option when you click edit field on multi-select"*, and this prop

   * is what makes that literal rather than approximate: the lane editor IS this component's Edit

   * pane, so it writes the SHARED field definition through the same `onRetype` upsert, obeys the

   * same permission wall, carries the same rename-by-row-identity migration and the same colour

   * swatches. A second options editor would have had to re-earn every one of those.

   *

   * Back then CLOSES β€” same rule as `initialPosition`: there is no action list behind a pane

   * that was opened directly.

   */
  initialPane?: MenuPane;
  /** Wave-6 item 9c β€” true on the cohort page: the create forms offer the Scope control

   *  ("This cohort table only" = DEFAULT vs "All customer tables"). */
  scopeChoice?: boolean;
  /** Wave-6 item 11c β€” pin state + actions. `onPinTo` absent when pinning would be a no-op

   *  (identity column, or already the boundary); `onUnpin` absent when nothing is pinned. */
  pinnedTo?: boolean;
  onPinTo?: () => void;
  onUnpin?: () => void;
  /**

   * Wave-2 item 8c: change the PERIOD of a measure-carrying column. Supplied for any field with

   * `.measure` β€” user-created `measure_*` columns and the pre-set measure fields alike. The

   * caller emits the ordinary `field_upsert` (and auto-renames the header when the user never

   * renamed it).

   */
  onPeriod?: (window: WindowSpec) => void;
  /**

   * Delete this USER-CREATED column outright (owner gap closed 2026-07-27). Supplied ONLY for

   * the deletable strata (`custom_` overlay fields, `measure_` formula columns) β€” absent means

   * the control is not rendered at all, so a base field cannot even be offered the action.

   */
  onDelete?: () => void;
  /** Wave-5 item 1 β€” Duplicate field. Supplied for creatable strata only (base Odoo fields

   *  offer no Duplicate β€” cloning the source of truth into an editable copy is out of scope). */
  onDuplicate?: () => void;
  /** Wave-5 item 1 β€” save a permissions change. Supplied iff the VIEWER may change them

   *  (isAdmin || createdBy === viewer.name, and only on creatable strata). */
  onPermissions?: (edit: "everyone" | "creator" | "admins") => void;
  /** Wave-5 item 10 β€” save a display format. Supplied for number/currency/formula and

   *  date/created_time fields. */
  onFormat?: (format: FieldFormat) => void;
  /** ⭐ WAVE-29 T33 (owner item 17) β€” set (or clear, with `undefined`) this column's SUMMARY: the

   *  value its group footers and the table's totals row show. Supplied wherever a field write is

   *  possible; the pane offers only what `aggregations.aggOptions` allows for the type. */
  onAggregate?: (agg: AggName | undefined) => void;
  /** Wave-5 item 1 β€” Sort by this field (replaces the view's sort), and the conditional

   *  clears (item 3). All of these mutate the EXISTING view config β€” no new host surface. */
  onSort: (dir: "asc" | "desc") => void;
  onClearSort: () => void;
  onFilterBy: () => void;
  onClearFilter: () => void;
  onGroupByField: () => void;
  onClearGroup: () => void;
  /** Assignable people, from the host's real user list. Empty = the host did not supply one,

   *  and "Assignee" is offered without choices rather than with invented ones. */
  userOptions?: string[];
  /**

   * CG-8's measures, reused as the vocabulary of a FORMULA-MEASURE column (owner item 7):

   * `Sales Β· the last 90 days` as a column the user creates. Empty = the semantic store is

   * unavailable here, and the option is simply not offered (same rule as measure conditions).

   */
  measures?: Measure[];
}

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

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

/**

 * The menu's panes (wave-5 item 2). The NOTE editor and the editors used to render inline in

 * the menu body; each opens its OWN dedicated window. One overlay, one pane at a time;

 * "menu" is the action list.

 *

 * Owner item 8 (2026-07-31): "edit" ABSORBS the former "rename" and "swap" panes β€” one

 * Airtable-grade Edit-field window owning the field's name, its type (with the per-type

 * choices/stars/formula config), and the Change-field control that swaps the column to show

 * another field.

 */
type MenuPane = "menu" | "note" | "edit" | "permissions" | "format" | "summary";

/**

 * How each creatable type reads in the menu. DERIVED from CREATABLE_TYPES rather than listed

 * again: a hand-maintained copy is a third place the vocabulary lives, and the failure mode is

 * silent β€” add a type to the contract, forget this list, and the type is accepted by the host,

 * asserted by the drift gate, and simply never offered to anyone.

 *

 * `Record<FieldType, string>` is what forces it: adding a member to the union without a label

 * here fails `tsc`, so the compiler is the gate and no test has to click a canvas header menu.

 *

 * Wave-8 I20: the map itself MOVED to icons.tsx, beside the per-type glyphs β€” a type's label

 * and its icon are one vocabulary, and splitting them across two files is how they drift.

 * Imported here; the totality guarantee above is unchanged (icons.tsx types it identically).

 */
const FIELD_TYPES = CREATABLE_TYPES.map((value) => ({ value, label: TYPE_LABELS[value] }));

/** Types whose choices are declared in an options editor at creation time. */
function needsOptions(t: FieldType | "measure"): boolean {
  return t === "select" || t === "multiselect";
}

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

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

/**

 * ⭐ WAVE 28 Β· R4 / C1 β€” how a SET-STATISTIC comparison reads in the operator list.

 *

 * β›” KEYED BY `RollupRefOp`, so the day `core.user_tables.ROLLUP_REF_OPS` gains or loses an

 * operator this map fails to compile rather than rendering a bare identifier β€” the same

 * discipline `ROLLUP_FN_LABELS` uses, and the reason the Οƒ picker maps `ROLLUP_REF_OPS` instead

 * of hand-filtering the full operator list.

 * ⚠ The wording names the STATISTIC, not the arithmetic: "2 Οƒ above the mean" is the sentence a

 * person is trying to write, and "is greater than mean + kΒ·stdev" is the implementation of it.

 */
/**

 * ⭐ MIRRORS `core.user_tables.ROLLUP_MAX_SIGMAS`, and `verify_rollup_editor.py` HOLDS THE TWO IN

 * STEP by importing the server's constant and comparing (a real enforcer this time β€” `types.ts`

 * spent a wave claiming one that contained zero occurrences of the word it guarded,

 * [[limit-with-no-enforcer]]).

 *

 * β›” WHY THE CONTROL MUST KNOW THE BOUND AT ALL. `_clean_rollup` REFUSES the whole field outside

 * this range β€” not the leaf, the FIELD β€” so an unbounded box invites a value and then answers a

 * 400 naming a cap the control never mentioned. That is `maxPosts` exactly: it offered 200 while

 * the save door refused anything over 12 ([[default-must-pass-its-own-guard]]). A control must

 * display what it will SEND.

 */
const MAX_SIGMAS = 10;

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

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

/**

 * ⭐⭐ 2026-08-09 (owner) β€” ONE CONDITION LIST, RENDERED TWICE, because a rollup now filters at

 * two different moments and they mean different things.

 *

 * Owner: *"instead of last 12 posts, we also want to make it so its last N record, where the

 * record's Status is video."* That is a filter the WINDOW must respect β€” pick the reels first,

 * then take the last 10 of them. The existing list is the opposite by design (wave 28 / C1 moved

 * it below the window so a `ref: {sigmas}` threshold is a statistic OF the rows being folded), so

 * the two cannot be one control.

 *

 * β›” EXTRACTED RATHER THAN COPIED. Two near-identical 130-line JSX blocks is how one of them

 * keeps offering an operator the other dropped β€” and the operator list here is already the

 * server's (`ROLLUP_REF_OPS`), so a hand-edited second copy would drift from `_clean_rollup`

 * silently ([[one-evaluator-per-question]]).

 * β›” `allowRef` IS A REFUSAL MIRRORED, NOT A UI PREFERENCE. `_clean_rollup` refuses a `ref` leaf

 * in `where` β€” before the window there is no fixed set for a mean to be about β€” so offering the

 * Οƒ operators there would be a control whose only outcome is a 400 on the whole field.

 */
function RollupConditionList({

  title,

  hint,

  conditions,

  onConditions,

  conj,

  onConj,

  targetFields,

  allowRef,

  idPrefix,

}: {

  title: string;

  hint: string;

  conditions: RollupCondition[];

  onConditions: (v: RollupCondition[]) => void;

  conj: "and" | "or";

  onConj: (v: "and" | "or") => void;

  targetFields: { key: string; label: string }[];

  allowRef: boolean;

  idPrefix: string;

}) {
  const patch = (index: number, next: RollupCondition) =>
    onConditions(conditions.map((item, i) => (i === index ? next : item)));
  return (
    <div className="cg-rollup-conditions">
      <div className="cg-rollup-conditions__head">
        <span>{title}</span>
        <button
          type="button"
          className="cg-btn"
          disabled={targetFields.length === 0 || conditions.length >= 20}
          onClick={() => onConditions([
            ...conditions,
            { field: targetFields[0]?.key ?? "", op: "eq", value: "" },
          ])}
        >
          Add condition
        </button>
      </div>
      {conditions.length > 1 ? (
        <select
          className="cg-input"
          aria-label={`Match all or any ${title.toLowerCase()} conditions`}
          value={conj}
          onChange={(event) => onConj(event.target.value as "and" | "or")}
        >
          <option value="and">All conditions must match</option>
          <option value="or">Any condition may match</option>
        </select>
      ) : null}
      {conditions.map((condition, index) => (
        <div className="cg-rollup-condition" key={`${idPrefix}-${index}-${condition.field}`}>
          <select
            className="cg-input"
            aria-label={`${title} condition ${index + 1} column`}
            value={condition.field}
            onChange={(event) => patch(index, { ...condition, field: event.target.value })}
          >
            {targetFields.map((targetField) => (
              <option key={targetField.key} value={targetField.key}>{targetField.label}</option>
            ))}
          </select>
          {/*
            ⭐⭐ WAVE 28 Β· R4 / C1 β€” THE THRESHOLD MAY BE THE SET'S OWN STATISTICS.
            Owner's request (Nurilab): an average of the last 10 posts with outliers trimmed β€”
            "anything beyond 2 sigma". That is not a new aggregator, it is a CONDITION whose
            threshold is computed from the scoped rows themselves: mean + k*stdev of the same
            column, over the window `sortBy`+`limit` kept, BEFORE these conditions filter.

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

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

let optionDraftSequence = 0;

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

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

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

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

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

function OptionsEditor({
  idPrefix,
  drafts,
  onDrafts,
  colorCode,
  onColorCode,
  type,
}: {
  idPrefix: string;
  drafts: OptionDraft[];
  onDrafts: (next: OptionDraft[]) => void;
  colorCode: boolean;
  onColorCode: (next: boolean) => void;
  type: FieldType | "measure";
}) {
  const update = (id: string, patch: Partial<OptionDraft>) =>
    onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
  const settings = optionSettings(drafts, type);
  return (
    <div className="cg-options-editor">
      <div className="cg-options-head">
        <strong>Options</strong>
        <label className="cg-option-toggle">
          <input
            type="checkbox"
            checked={colorCode}
            onChange={(event) => onColorCode(event.target.checked)}
          />
          <span>Color-code options</span>
        </label>
      </div>
      <div className="cg-option-list">
        {drafts.map((draft, index) => (
          <div className="cg-option-row" key={draft.id}>
            <SwatchPicker
              value={
                normalizeOptionColor(draft.color) ??
                OPTION_PALETTE[index % OPTION_PALETTE.length].bg
              }
              disabled={!colorCode}
              label={draft.label || `option ${index + 1}`}
              onPick={(hex) => update(draft.id, { color: hex })}
            />
            <input
              id={`${idPrefix}-${draft.id}`}
              className="cg-input cg-option-name"
              type="text"
              maxLength={120}
              value={draft.label}
              placeholder="Option name"
              aria-label={`Option ${index + 1}`}
              onChange={(event) => {
                const label =
                  type === "multiselect"
                    ? event.target.value.replace(/,/g, " ")
                    : event.target.value;
                update(draft.id, { label });
              }}
              onKeyDown={(event) => {
                if (event.key !== "Enter") return;
                event.preventDefault();
                onDrafts([
                  ...drafts,
                  {
                    id: nextOptionDraftId(),
                    label: "",
                    color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
                  },
                ]);
              }}
            />
            <button
              type="button"
              className="cg-option-remove"
              aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
              title="Remove option"
              onClick={() => onDrafts(drafts.filter((item) => item.id !== draft.id))}
            >
              <svg viewBox="0 0 16 16" aria-hidden="true">
                <path d="M4 4l8 8M12 4l-8 8" />
              </svg>
            </button>
          </div>
        ))}
      </div>
      <button
        type="button"
        className="cg-option-add"
        onClick={() =>
          onDrafts([
            ...drafts,
            {
              id: nextOptionDraftId(),
              label: "",
              color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
            },
          ])
        }
      >
        Add option
      </button>
      <span className="cg-field-hint">
        {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
        {type === "multiselect" && " Commas inside an option are not supported."}
      </span>
    </div>
  );
}

/**
 * The create-picker's kind: a creatable overlay type, or the FORMULA-MEASURE pseudo-kind.
 * "measure" is deliberately NOT a FieldType β€” a measure column's real type comes from the
 * measure itself (currency/int/pct), and widening the union would let it leak into every
 * switch that renders cells.
 */
type CreateKind = FieldType | "measure";

/**
 * Owner item 8 (2026-07-31) β€” the create pane's field-type picker: a find box over an icon
 * listbox, replacing the icon-less native select. Each row wears the SAME mark its column
 * header will wear (`FieldTypeIcon` ← TYPE_SHAPES), so the vocabulary teaches itself. The
 * "measure" pseudo-kind borrows the currency mark: a measure column's real type is
 * currency/int/pct, and inventing a 17th glyph for a pseudo-kind would put a mark on screen
 * that no column ever wears.
 */
function TypePicker({
  value,
  onPick,
  offerMeasure,
  only,
}: {
  value: CreateKind;
  onPick: (k: CreateKind) => void;
  offerMeasure: boolean;
  /** Restrict the list (the Edit-field pane passes RETYPE_TYPES β€” the overlay-editable
   *  strata a created field may become). Absent = every creatable type. */
  only?: readonly FieldType[];
}) {
  const [q, setQ] = useState("");
  const needle = q.trim().toLowerCase();
  const base = only
    ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
    : FIELD_TYPES;
  const rows: { value: CreateKind; label: string }[] = [
    ...base,
    // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
    // of jargon and a parenthetical, replaced by the word people already use for the thing.
    // The internal key stays `measure` β€” see the C-NAME amendment in the wave doc.
    ...(offerMeasure
      ? [{ value: "measure" as CreateKind, label: "Metric" }]
      : []),
  ].filter((r) => !needle || r.label.toLowerCase().includes(needle));
  return (
    <div className="cg-type-picker">
      <div className="cg-type-search">
        <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true">
          <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
          <path
            d="m10.4 10.4 3.1 3.1"
            stroke="currentColor"
            strokeWidth="1.35"
            strokeLinecap="round"
          />
        </svg>
        <input
          type="text"
          value={q}
          placeholder="Find a field type"
          aria-label="Find a field type"
          onChange={(event) => setQ(event.target.value)}
        />
      </div>
      <div className="cg-type-list" role="listbox" aria-label="Field type">
        {rows.map((r) => (
          <button
            key={r.value}
            type="button"
            role="option"
            aria-selected={value === r.value}
            className={"cg-type-row" + (value === r.value ? " is-on" : "")}
            onClick={() => onPick(r.value)}
          >
            <FieldTypeIcon type={r.value === "measure" ? "currency" : r.value} size={16} />
            <span className="cg-type-label">{r.label}</span>
            {value === r.value && (
              <svg
                className="cg-type-check"
                width="14"
                height="14"
                viewBox="0 0 16 16"
                fill="none"
                aria-hidden="true"
              >
                <path
                  d="m3.5 8.5 3 3 6-6.5"
                  stroke="currentColor"
                  strokeWidth="1.6"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            )}
          </button>
        ))}
        {rows.length === 0 && <div className="cg-pop-note">No matching type.</div>}
      </div>
    </div>
  );
}

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

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

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

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

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

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

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

/**
 * Wave-5 items 9/11 β€” the extra editors a new field's type may need, shared VERBATIM by the
 * two create surfaces (insert-field and Change-field's "New field" half) so the two doors
 * cannot drift: a FORMULA gets its source editor with live validation and a reference picker;
 * a RATING gets its star count (the contract's 2..10).
 */
function ExtraTypeEditor({
  kind,
  fields,
  formulaText,
  onFormulaText,
  formulaError,
  maxValue,
  onMaxValue,
  codeLanguage,
  onCodeLanguage,
  idPrefix,
  showFormulaHelp = true,
  automationKind = "instagram_profile",
  onAutomationKind,
  automationUrlField = "",
  onAutomationUrlField,
  linkTargets = [],
  linkTable = "",
  onLinkTable,
  linkSingle = false,
  onLinkSingle,
  rollupMode = "link",
  onRollupMode,
  rollupSourceOffer = { topics: [], windows: [] },
  rollupSource = { topic: "", measure: "", groupBy: "", on: "", window: "ytd" },
  onRollupSource,
  rollupLink = "",
  onRollupLink,
  rollupField = "",
  onRollupField,
  rollupFn = "sum",
  onRollupFn,
  rollupLimit = 0,
  onRollupLimit,
  rollupSortBy = "",
  onRollupSortBy,
  rollupDistinctBy = "",
  onRollupDistinctBy,
  rollupWhere = [],
  onRollupWhere,
  rollupWhereConj = "and",
  onRollupWhereConj,
  rollupConditions = [],
  onRollupConditions,
  rollupConditionConj = "and",
  onRollupConditionConj,
}: {
  kind: FieldType | "measure";
  fields: Field[];
  formulaText: string;
  onFormulaText: (v: string) => void;
  formulaError: string | null;
  maxValue: number;
  onMaxValue: (n: number) => void;
  /** ⭐ Wave-27 item 13 (R13) β€” the code column's language draft. REQUIRED at every call site,
   *  unlike the `automation` drafts below it: this pane RENDERS a <select> for a `code` kind, and
   *  an unwired one would be a control that configures nothing, which is worse than no control
   *  ([[wrong-parent-not-broken-control]]). Every mount can reach the kind, so every mount says
   *  which draft it is editing. */
  codeLanguage: string;
  onCodeLanguage: (v: string) => void;
  idPrefix: string;
  showFormulaHelp?: boolean;
  /** C5-AUTOFIELD β€” the automation column's config drafts. Optional so the call sites that
   *  cannot reach an automation type (the Change-field "new field" form) need no change. */
  automationKind?: string;
  onAutomationKind?: (v: string) => void;
  automationUrlField?: string;
  onAutomationUrlField?: (v: string) => void;
  /** ⭐ 2026-08-07 β€” the relational drafts. Optional for the same reason the automation ones
   *  are: the Change-field "new field" form reaches these kinds too, and a call site that does
   *  not offer them should need no change. */
  linkTargets?: LinkTarget[];
  linkTable?: string;
  onLinkTable?: (v: string) => void;
  linkSingle?: boolean;
  onLinkSingle?: (v: boolean) => void;
  /** ⭐ 2026-08-09 β€” which KIND of rollup is being built. `"link"` folds workspace rows;
   *  `"source"` reads through to a governed Odoo topic without copying a row into the store. */
  rollupMode?: "link" | "source";
  onRollupMode?: (v: "link" | "source") => void;
  rollupSourceOffer?: RollupSourceOffer;
  rollupSource?: RollupSource;
  onRollupSource?: (v: RollupSource) => void;
  rollupLink?: string;
  onRollupLink?: (v: string) => void;
  rollupField?: string;
  onRollupField?: (v: string) => void;
  rollupFn?: RollupFn;
  onRollupFn?: (v: RollupFn) => void;
  rollupLimit?: number;
  onRollupLimit?: (v: number) => void;
  rollupSortBy?: string;
  onRollupSortBy?: (v: string) => void;
  rollupDistinctBy?: string;
  onRollupDistinctBy?: (v: string) => void;
  /** ⭐⭐ 2026-08-09 β€” the PRE-filter (`rollup.where`): which linked records the window may
   *  spend its slots on. Separate from `rollupConditions`, which runs after it. */
  rollupWhere?: RollupCondition[];
  onRollupWhere?: (v: RollupCondition[]) => void;
  rollupWhereConj?: "and" | "or";
  onRollupWhereConj?: (v: "and" | "or") => void;
  rollupConditions?: RollupCondition[];
  onRollupConditions?: (v: RollupCondition[]) => void;
  rollupConditionConj?: "and" | "or";
  onRollupConditionConj?: (v: "and" | "or") => void;
}) {
  if (kind === "formula") {
    // 2026-07-31 (owner item 2): other FORMULA fields are referencable now β€” evaluation is
    // topological and a cycle is refused at validation, so the old exclusion is gone.
    const referencable = fields.filter((f) => f.key !== "__proto__");
    return (
      <>
        <label>
          <span>Formula</span>
          <textarea
            className="cg-input cg-formula-editor"
            rows={3}
            value={formulaText}
            placeholder={"MAX(0, {revenue_ly} - {revenue_ytd})"}
            aria-label="Formula"
            onChange={(event) => onFormulaText(event.target.value)}
          />
        </label>
        <div className="cg-cond-line cg-formula-insert">
          <FieldSelectButton
            ariaLabel="Insert a field reference"
            placeholder="Insert a field reference…"
            // An ACTION picker, not a value one: it never holds a selection, so it stays in
            // the placeholder state and `keepOpen` lets a formula take three references
            // without three trips through the button.
            value={undefined}
            keepOpen
            onChange={(key) =>
              onFormulaText((formulaText + " {" + key + "}").trimStart())
            }
            fields={referencable.map((f) => ({
              key: f.key, label: f.label, type: f.type,
            }))}
          />
        </div>
        {/*
          ⭐ 2026-08-10 β€” THE BLANK TRAP, said before it is hit rather than after.

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

          The idiom is Excel's own: the AGGREGATE functions skip blanks, so `SUM({b}, 0)` is
          "b, or nothing at all". Shown ALWAYS, not folded into the function list under
          `showFormulaHelp` β€” a list of 30 names is reference, and this is the one sentence
          that changes what somebody types. Kept to one line (DESIGN.md Β§4).
        */}
        <div className="cg-field-hint cg-formula-blank-hint">
          A blank in any part blanks the whole result. Wrap an optional column as{" "}
          {"SUM({field}, 0)"} to read it as zero.
        </div>
        {formulaText.trim() !== "" && formulaError ? (
          <div className="cg-field-hint cg-formula-error">{formulaError}</div>
        ) : showFormulaHelp ? (
          <div className="cg-field-hint">
            Excel-style: numbers, text in quotes, {"{field}"} references, + βˆ’ Γ— Γ· ^ &amp; ( ),
            IF Β· AND Β· OR Β· SUM Β· AVERAGE Β· COUNT Β· MIN Β· MAX Β· ROUND(UP/DOWN) Β· ABS Β· MOD Β·
            SQRT Β· CONCATENATE Β· LEFT Β· RIGHT Β· MID Β· LEN Β· TRIM Β· UPPER Β· LOWER Β· PROPER Β·
            TEXT Β· VALUE Β· TODAY Β· DAYS Β· YEAR Β· MONTH Β· DAY Β· IFERROR Β· ISBLANK.
            Errors show a blank cell.
          </div>
        ) : null}
      </>
    );
  }
  if (kind === "rating") {
    return (
      <label>
        <span>Number of stars</span>
        <input
          id={`${idPrefix}-rating-max`}
          className="cg-input cg-rating-max"
          type="number"
          min={2}
          max={10}
          value={maxValue}
          aria-label="Number of stars"
          onChange={(event) => {
            const n = Math.round(Number(event.target.value));
            onMaxValue(Number.isFinite(n) ? Math.max(2, Math.min(10, n)) : 5);
          }}
        />
      </label>
    );
  }
  if (kind === "code") {
    // ⭐ Wave-27 item 13 (R13) β€” the create form's only code-specific question. The hint is not
    // decoration: "code" in a product that also runs automations invites the assumption that
    // picking a language makes the snippet executable, and R13 is explicit that there is no
    // execution engine. Saying so at the moment of choosing is cheaper than a support answer.
    return (
      <label>
        <span>Language</span>
        <select
          id={`${idPrefix}-code-language`}
          className="cg-select"
          value={codeLanguage}
          aria-label="Code language"
          onChange={(event) => onCodeLanguage(event.target.value)}
        >
          {CODE_LANGUAGES.map((lang) => (
            <option key={lang} value={lang}>
              {CODE_LANGUAGE_LABELS[lang]}
            </option>
          ))}
        </select>
        <span className="cg-field-hint">
          Chooses how the snippet is coloured. It is never run.
        </span>
      </label>
    );
  }
  if (kind === "created_time") {
    return (
      <div className="cg-field-hint">
        Read-only. When the record was created in the source system.
      </div>
    );
  }
  if (kind === "automation") {
    // C5-AUTOFIELD β€” the field's GEAR. An automation column has no value the user types, so
    // this pane configures what a RUN does instead: which job, and which column carries the
    // thing it reads. The schedule and the Run-now button are NOT here β€” they belong to the
    // automation itself, on the Automation surface, because one job can fill a column across
    // many records and its cadence is a property of the job, not of the column.
    const urlish = fields.filter((f) => f.type === "url" || f.type === "text");
    const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
      ?? AUTOMATION_KINDS[0];
    return (
      <>
        <label>
          <span>What it reads</span>
          <select
            id={`${idPrefix}-automation-kind`}
            className="cg-input"
            value={automationKind}
            aria-label="Automation kind"
            onChange={(event) => onAutomationKind?.(event.target.value)}
          >
            {AUTOMATION_KINDS.map((k) => (
              <option key={k.key} value={k.key}>
                {k.label}
              </option>
            ))}
          </select>
        </label>
        <label>
          <span>URL column</span>
          <select
            id={`${idPrefix}-automation-url`}
            className="cg-input"
            value={automationUrlField}
            aria-label="URL column"
            onChange={(event) => onAutomationUrlField?.(event.target.value)}
          >
            <option value="">Choose a column…</option>
            {urlish.map((f) => (
              <option key={f.key} value={f.key}>
                {f.label}
              </option>
            ))}
          </select>
        </label>
        <div className="cg-field-hint">{chosen.hint}</div>
        <div className="cg-field-hint">
          Cells here are written by the run and cannot be typed into β€” a value you entered
          would be replaced by the next run without saying so.
        </div>
        {/* A v1 LIMIT, said out loud rather than discovered. The column can be created on any
            table, but an Instagram automation only accepts a blank database as its target
            (`clean_config('field_instagram')`), because the run writes rows and an Odoo-sourced
            table is read-only at the source. Without this line a user creates the column on
            Customer, goes to Automation, and finds no way to point anything at it. */}
        <div className="cg-field-hint">
          Runs target a blank database. On a connector-backed table this column can be created
          but no automation can write to it yet.
        </div>
      </>
    );
  }
  if (kind === "link") {
    // ⭐ 2026-08-07 β€” Airtable's "Link to another record", and the whole editor is ONE question:
    // which database. The relation itself is then the cell (a set of linked rows).
    return (
      <>
        <label>
          <span>Database</span>
          <select
            id={`${idPrefix}-link-table`}
            className="cg-input"
            value={linkTable}
            aria-label="Database to link to"
            onChange={(event) => onLinkTable?.(event.target.value)}
          >
            <option value="">Choose a database…</option>
            {linkTargets.map((t) => (
              <option key={t.key} value={t.key}>{t.label}</option>
            ))}
          </select>
        </label>
        {linkTargets.length === 0 ? (
          <div className="cg-field-hint">
            There is no other database to link to yet. Create one first, then come back.
          </div>
        ) : null}
        <label className="cg-cond-line">
          <input
            type="checkbox"
            checked={linkSingle}
            aria-label="Allow only one linked record"
            onChange={(event) => onLinkSingle?.(event.target.checked)}
          />
          <span>Allow only one linked record</span>
        </label>
        <div className="cg-field-hint">
          A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
          column of those records β€” an average, a total, a count.
        </div>
      </>
    );
  }
  if (kind === "rollup") {
    // ⭐ 2026-08-07 β€” Airtable's rollup, plus the LAST-N window Airtable does not have.
    //
    // The editor reads as the sentence the column answers, in order: through WHICH relation, over
    // WHICH column, folded HOW, and across WHICH records. That last control is the owner's
    // headline ("average Views over last N posts") and Airtable cannot express it β€” its rollup
    // conditions filter by predicate, never by rank.
    const linkFields = fields.filter((f) => f.type === "link");
    const chosenLink = linkFields.find((f) => f.key === rollupLink);
    const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
    const targetFields = target?.fields ?? [];
    // β›” COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN β€” it counts linked RECORDS, so the
    // field picker would be a control that configures nothing. Airtable's rule, and ours.
    const needsField = rollupFn !== "countall";
    // ⭐⭐ 2026-08-09 β€” THE SECOND KIND OF ROLLUP. Everything above summarises rows that live in
    // this workspace; a SOURCE rollup summarises rows that were never copied here β€” one grouped
    // SQL query over the governed Odoo model answers every parent row at once. That is the only
    // way a column can total 256,810 order lines, which is 4x what a database here may hold.
    const sourceTopics = rollupSourceOffer.topics;
    const topic = sourceTopics.find((t) => t.key === rollupSource.topic);
    const dim = topic?.dims.find((d) => d.key === rollupSource.groupBy);
    const setSource = (patch: Partial<RollupSource>) =>
      onRollupSource?.({ ...rollupSource, ...patch });
    // ⚠ A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
    // comma-joined id list and a computed value respectively, so neither can ever match.
    const joinable = fields.filter(
      (f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
    );
    const sourceEditor = (
      <>
        <label>
          <span>Odoo data</span>
          <select
            id={`${idPrefix}-rollup-topic`}
            className="cg-input"
            value={rollupSource.topic}
            aria-label="Odoo topic"
            onChange={(event) =>
              // β›” CLEAR THE MEASURE AND THE DIM WITH THE TOPIC. Both are keys OF the topic, so
              // carrying them across a topic change leaves a bag naming a measure the new topic
              // does not have β€” which the save door refuses, on a form that looks complete.
              setSource({ topic: event.target.value, measure: "", groupBy: "" })
            }
          >
            <option value="">Choose what to summarise…</option>
            {sourceTopics.map((t) => (
              <option key={t.key} value={t.key}>{t.label}</option>
            ))}
          </select>
        </label>
        {sourceTopics.length === 0 ? (
          <div className="cg-field-hint">
            No live data sources are available for this workspace. A source rollup reads a
            connected system; this one has none connected yet.
          </div>
        ) : null}
        {topic ? (
          <>
            <label>
              <span>Measure</span>
              <select
                id={`${idPrefix}-rollup-measure`}
                className="cg-input"
                value={rollupSource.measure}
                aria-label="Measure"
                onChange={(event) => setSource({ measure: event.target.value })}
              >
                <option value="">Choose a measure…</option>
                {topic.measures.map((m) => (
                  <option key={m.key} value={m.key}>{m.label}</option>
                ))}
              </select>
            </label>
            <label>
              <span>One row per</span>
              <select
                id={`${idPrefix}-rollup-dim`}
                className="cg-input"
                value={rollupSource.groupBy}
                aria-label="Group by"
                onChange={(event) => setSource({ groupBy: event.target.value })}
              >
                <option value="">Choose a grouping…</option>
                {topic.dims.map((d) => (
                  <option key={d.key} value={d.key}>{d.label}</option>
                ))}
              </select>
            </label>
            <label>
              <span>Matched on</span>
              <select
                id={`${idPrefix}-rollup-on`}
                className="cg-input"
                value={rollupSource.on}
                aria-label="Column to match on"
                onChange={(event) => setSource({ on: event.target.value })}
              >
                <option value="">Choose this database's column…</option>
                {joinable.map((f) => (
                  <option key={f.key} value={f.key}>{f.label}</option>
                ))}
              </select>
            </label>
            {/* ⚠ THE JOIN IS THE ONE THING THE SERVER CANNOT CHECK. It knows the measure exists
                and the dim is groupable; it cannot know that THIS column holds the same kind of
                value the grouping keys by. A wrong match is not an error β€” it is a column of
                blanks. So the control says which kind of value it needs. */}
            {dim ? (
              <div className="cg-field-hint">
                {dim.keyedBy === "id"
                  ? `Pick the column holding the Odoo ID for ${dim.label.toLowerCase()}. Matching on a name instead leaves every cell blank.`
                  : `Pick the column holding the ${dim.label.toLowerCase()} value itself β€” this grouping keys by its own value, not by an ID.`}
              </div>
            ) : null}
            <label>
              <span>Over</span>
              <select
                id={`${idPrefix}-rollup-window`}
                className="cg-input"
                value={rollupSource.window || "all_time"}
                aria-label="Date window"
                onChange={(event) => setSource({ window: event.target.value })}
              >
                {rollupSourceOffer.windows.map((w) => (
                  <option key={w.key} value={w.key}>{w.label}</option>
                ))}
              </select>
            </label>
            <div className="cg-field-hint">
              Recomputed against live data β€” the window moves with today's date rather than
              freezing the dates it was created on.
            </div>
          </>
        ) : null}
      </>
    );
    const linkEditor = (
      <>
        <label>
          <span>Through</span>
          <select
            id={`${idPrefix}-rollup-link`}
            className="cg-input"
            value={rollupLink}
            aria-label="Link column"
            onChange={(event) => onRollupLink?.(event.target.value)}
          >
            <option value="">Choose a link column…</option>
            {linkFields.map((f) => (
              <option key={f.key} value={f.key}>{f.label}</option>
            ))}
          </select>
        </label>
        {linkFields.length === 0 ? (
          <div className="cg-field-hint">
            This database has no link column yet. A rollup summarises records reached through a
            link, so add one of those first.
          </div>
        ) : null}
        <label>
          <span>Fold</span>
          <select
            id={`${idPrefix}-rollup-fn`}
            className="cg-input"
            value={rollupFn}
            aria-label="Rollup function"
            onChange={(event) => onRollupFn?.(event.target.value as RollupFn)}
          >
            {ROLLUP_FNS.map((fn) => (
              <option key={fn} value={fn}>{ROLLUP_FN_LABELS[fn]}</option>
            ))}
          </select>
        </label>
        {needsField ? (
          <label>
            <span>Column</span>
            <select
              id={`${idPrefix}-rollup-field`}
              className="cg-input"
              value={rollupField}
              aria-label="Column to roll up"
              onChange={(event) => onRollupField?.(event.target.value)}
            >
              <option value="">Choose a column…</option>
              {targetFields.map((f) => (
                <option key={f.key} value={f.key}>{f.label}</option>
              ))}
            </select>
          </label>
        ) : null}
        {/*
          ⭐⭐ 2026-08-09 Β· D-99 β€” THE STATE THE OWNER'S REPORT DESCRIBES, SAID OUT LOUD.
          Owner: *"if we want to use Rollup field to apply to the related database, it doesn't
          work. Because the linked Field can't be selected yet."*

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

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

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

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

export default function ColumnMenu({
  state,
  field,
  fields,
  linkTargets = [],
  rollupSourceOffer = { topics: [], windows: [] },
  locked,
  schemaLocked = false,
  viewer,
  sortedDir,
  isFiltered,
  isGrouped,
  groupable,
  onClose,
  onNote,
  onHide,
  onCreate,
  onChangeField,
  onCreateAndSwap,
  onProfileFlag,
  onRetype,
  onFieldConfig,
  onRename,
  onFormula,
  initialPosition,
  initialPane,
  scopeChoice = false,
  pinnedTo = false,
  onPinTo,
  onUnpin,
  onPeriod,
  onDelete,
  onDuplicate,
  onPermissions,
  onFormat,
  onAggregate,
  onSort,
  onClearSort,
  onFilterBy,
  onClearFilter,
  onGroupByField,
  onClearGroup,
  userOptions = [],
  measures = [],
}: ColumnMenuProps) {
  const [pane, setPane] = useState<MenuPane>(schemaLocked ? "menu" : initialPane ?? "menu");
  const [note, setNote] = useState(field.note ?? "");
  const [position, setPosition] = useState<CreatePosition | null>(initialPosition ?? null);
  /** Delete is DESTRUCTIVE (a custom field's stored values go with it) β€” first click arms,
   *  second click fires. Reopening the menu disarms (state is per-mount, keyed by field). */
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [label, setLabel] = useState("");
  /** Whether the user has typed their own name β€” an auto-suggested measure label must never
   *  overwrite one, but should keep tracking the measure/window until they do. */
  const [labelTouched, setLabelTouched] = useState(false);
  const [kind, setKind] = useState<CreateKind>("text");
  const [createOptionDrafts, setCreateOptionDrafts] = useState<OptionDraft[]>(() =>
    optionDrafts(DEFAULT_OPTION_LABELS)
  );
  const [createColorCode, setCreateColorCode] = useState(true);
  const [measureKey, setMeasureKey] = useState(measures[0]?.key ?? "");
  const [measureWindow, setMeasureWindow] = useState<WindowSpec>(DEFAULT_MEASURE_WINDOW);
  /** Wave-5 item 9/11 β€” the create form's formula source and rating star count. */
  const [formulaText, setFormulaText] = useState("");
  const [maxValue, setMaxValue] = useState(5);
  /** ⭐ Wave-27 item 13 (R13) β€” the create form's code LANGUAGE. Seeded to `plain`, which is
   *  also what an absent bag means, so creating without touching this stores nothing extra. */
  const [codeLanguage, setCodeLanguage] = useState<string>("plain");
  /** C5-AUTOFIELD β€” the create form's automation config. */
  const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
  const [automationUrlField, setAutomationUrlField] = useState(
    () => fields.find((f) => f.type === "url")?.key ?? ""
  );
  /**
   * ⭐ 2026-08-07 β€” the create form's LINK and ROLLUP configuration.
   *
   * β›” BOTH KINDS ARE UNCREATABLE WITHOUT THEIR BAG β€” `core.user_tables._clean_field` returns
   * None for a `link` with no `link` bag and for a `rollup` with no `rollup` bag β€” so `canCreate`
   * gates on these below rather than letting the server refuse a column the user just named.
   * That refusal would be silent in the worst way: created, named, configured, gone on reload.
   */
  const [linkTable, setLinkTable] = useState("");
  const [linkSingle, setLinkSingle] = useState(false);
  /** ⭐ 2026-08-09 β€” the read-through half. `rollupMode` decides which bag `extraFor` builds;
   *  the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
   *  shape before it ever reads `link`. */
  const [rollupMode, setRollupMode] = useState<"link" | "source">("link");
  const [rollupSource, setRollupSource] = useState<RollupSource>({
    topic: "", measure: "", groupBy: "", on: "", window: "ytd",
  });
  const [rollupLink, setRollupLink] = useState("");
  const [rollupField, setRollupField] = useState("");
  const [rollupFn, setRollupFn] = useState<RollupFn>("sum");
  /** 0 = every linked record (Airtable's only behaviour). Non-zero needs a sort β€” see below. */
  const [rollupLimit, setRollupLimit] = useState(0);
  const [rollupSortBy, setRollupSortBy] = useState("");
  const [rollupDistinctBy, setRollupDistinctBy] = useState("");
  const [rollupWhere, setRollupWhere] = useState<RollupCondition[]>([]);
  const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
  const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
  const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
  const [swapTo, setSwapTo] = useState("");
  /** The "New field" half of Change-field keeps its own name/options β€” a half-typed insert
   *  form must not leak into a swap and vice versa. */
  const [swapLabel, setSwapLabel] = useState("");
  const [swapOptionDrafts, setSwapOptionDrafts] = useState<OptionDraft[]>(() =>
    optionDrafts(DEFAULT_OPTION_LABELS)
  );
  const [swapColorCode, setSwapColorCode] = useState(true);
  const [swapFormulaText, setSwapFormulaText] = useState("");
  const [swapMaxValue, setSwapMaxValue] = useState(5);
  /** ⭐ Wave-27 item 13 (R13) β€” the swap form's OWN language draft. It gets one rather than
   *  reading the create form's, because `extraFor` used to close over the create drafts and the
   *  swap path passes its own `src`/`starCount` in for exactly that reason: two forms sharing a
   *  draft means changing a language in one silently changes what the other will save. */
  const [swapCodeLanguage, setSwapCodeLanguage] = useState<string>("plain");
  /** Item 8c β€” the period DRAFT. null = untouched (the field's own window shows). Buffered
   *  behind an Apply rather than emitted per keystroke: a custom range is typed one date at a
   *  time, and each emit is a full host round trip that would repaint the column half-ready. */
  const [periodDraft, setPeriodDraft] = useState<WindowSpec | null>(null);
  /** Permissions pane draft. */
  const [permDraft, setPermDraft] = useState<"everyone" | "creator" | "admins">(
    field.permissions?.edit ?? "everyone"
  );
  /** Format pane draft β€” seeded from the field, saved whole. */
  const [fmtDraft, setFmtDraft] = useState<FieldFormat>(() => ({ ...(field.format ?? {}) }));
  /** Item 9c β€” the create forms' Scope draft. 'cohort' is the DEFAULT per the contract. */
  const [scopeDraft, setScopeDraft] = useState<FieldScope>("cohort");
  /** The Edit pane's NAME draft, seeded from the current label (wave-6 item 5's rename,
   *  re-homed into the Edit-field pane by owner item 8). */
  const [renameDraft, setRenameDraft] = useState(field.label);
  /** Owner item 8 β€” the Edit pane's TYPE draft plus the per-type config drafts: options
   *  prefilled from the field (a select retyped to multi select keeps its choices), star
   *  count from the field's own max, formula source from the field's own source. */
  const [editType, setEditType] = useState<FieldType>(field.type);
  const [editOptionDrafts, setEditOptionDrafts] = useState<OptionDraft[]>(() =>
    optionDrafts(
      choiceOptions(field).length ? choiceOptions(field) : DEFAULT_OPTION_LABELS,
      field.optionColors
    )
  );
  /** Item 15 (C-RENAME) β€” what each option ROW said when the editor opened, by draft id. A ref,
   *  not state: it is the fixed point the renames are measured against and it must not move
   *  while the user types. Seeded from the same call that seeds the drafts, so the two cannot
   *  disagree about which row is which. */
  const editOptionOrigin = useRef<Map<string, string>>(new Map());
  if (editOptionOrigin.current.size === 0 && editOptionDrafts.length)
    editOptionOrigin.current = new Map(
      editOptionDrafts.map((draft) => [draft.id, draft.label.trim()])
    );
  const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
  const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
  const [editFormulaText, setEditFormulaText] = useState(() =>
    typeof field.formula === "string" ? field.formula : ""
  );
  /** C5-AUTOFIELD β€” the Edit pane's automation drafts, seeded from the field's own config. */
  const [editAutomationKind, setEditAutomationKind] = useState(
    () => field.automation?.kind ?? AUTOMATION_KINDS[0].key
  );
  const [editAutomationUrlField, setEditAutomationUrlField] = useState(
    () => field.automation?.urlField ?? ""
  );
  /** ⭐ Wave-27 item 13 (R13) β€” the Edit pane's language draft, seeded from the field's own bag
   *  through the shared resolver (never `field.code!.language`: an unconfigured code column is
   *  the common case, and `codeLanguageOf` is the one place that answers what absent means). */
  const [editCodeLanguage, setEditCodeLanguage] = useState<string>(() => codeLanguageOf(field));
  /**
   * ⭐⭐ 2026-08-09 (owner) β€” THE EDIT PANE'S OWN RELATIONAL DRAFT, seeded from the field's bag.
   *
   * Owner: *"even when i click edit field for rollup, it doesn't actually show me the
   * configuration that I use to generate it, it only shows change to a different field."*
   * Exactly right, and it was worse than missing: `RETYPE_TYPES` includes `rollup`, so the pane
   * offered a type picker whose "Rollup" option would re-save the column with NO bag.
   *
   * β›” ONE OBJECT, NOT TWELVE `useState`s, and the reason is seeding. Every draft here must start
   * as what the STORE holds β€” a pane that opens on defaults and then saves them is a pane that
   * silently rewrites a working column the moment somebody opens it to look. One object seeded
   * once from `field.rollup` makes "opened but unchanged" literally equal to the stored bag, so
   * the dirty check below is an object comparison rather than twelve remembered pairs.
   */
  type RollupBag = NonNullable<Field["rollup"]>;
  const [editRollup, setEditRollup] = useState<RollupBag>(() => ({ ...(field.rollup ?? {}) }));
  const patchEditRollup = (patch: Partial<RollupBag>) =>
    setEditRollup((current) => {
      const next = { ...current, ...patch } as RollupBag;
      // β›” AN EMPTY LIST IS AN ABSENT KEY, matching what `extraFor` sends on the create path and
      // what `_clean_rollup` stores. Otherwise "remove the last condition" would save
      // `conditions: []` while the stored bag has no such key, and the column would read as
      // dirty forever.
      for (const key of ["where", "conditions"] as const) {
        if (Array.isArray(next[key]) && next[key]!.length === 0) {
          delete next[key];
          delete next[key === "where" ? "whereConj" : "conditionConj"];
        }
      }
      if (!next.sortBy) {
        // The server refuses a limit with no declared order; dropping both together keeps the
        // draft in a shape that can always be saved.
        delete next.limit;
        delete next.sortDir;
      }
      return next;
    });
  const [editLinkTable, setEditLinkTable] = useState(() => field.link?.table ?? "");
  const [editLinkSingle, setEditLinkSingle] = useState(() => field.link?.single === true);

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

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

  // Wave-5 item 9, amended 2026-07-31 (owner item 2) β€” live formula validation for BOTH
  // create surfaces. Refs may now name OTHER formula fields (evaluation is topological);
  // what is refused is a CYCLE, checked against every formula's SOURCE. Both surfaces here
  // CREATE a field, so no cycle is possible yet and no selfKey is passed β€” the retype path
  // (in-place formula edit) would pass the edited field's key.
  const knownKeys = useMemo(
    () => new Set(fields.filter((f) => f.type !== "formula").map((f) => f.key)),
    [fields]
  );
  const formulaSources = useMemo(() => {
    const out = new Map<string, string>();
    for (const f of fields) {
      if (f.type !== "formula") continue;
      const src = typeof f.formula === "string" ? f.formula : "";
      if (src) out.set(f.key, src);
    }
    return out;
  }, [fields]);
  const formulaCheck = useMemo(
    () =>
      formulaText.trim() === ""
        ? { ok: false, error: "Type a formula", refs: [] as string[] }
        : validateFormula(formulaText, knownKeys, formulaSources),
    [formulaText, knownKeys, formulaSources]
  );
  const swapFormulaCheck = useMemo(
    () =>
      swapFormulaText.trim() === ""
        ? { ok: false, error: "Type a formula", refs: [] as string[] }
        : validateFormula(swapFormulaText, knownKeys, formulaSources),
    [swapFormulaText, knownKeys, formulaSources]
  );

  const chosenMeasure = measures.find((m) => m.key === measureKey);
  /** The suggested name reads as the sentence the column answers: "Sales Β· the last 90 days". */
  const suggestedLabel = chosenMeasure
    ? `${chosenMeasure.label} Β· ${windowLabel(measureWindow)}`
    : "";
  const effectiveLabel =
    kind === "measure" && !labelTouched && !label.trim() ? suggestedLabel : label;

  // A select with no choices is a column nothing can ever be put in, so creation is blocked
  // until it has at least one. An assignee takes its choices from the host, not from here.
  // A measure column needs a measure; a formula column needs a formula that PARSES β€” an
  // unparseable formula would be a permanently blank column, refused here rather than shipped.
  const canCreate =
    effectiveLabel.trim() !== "" &&
    (!needsOptions(kind) || options.length > 0) &&
    (kind !== "measure" || !!chosenMeasure) &&
    (kind !== "formula" || formulaCheck.ok) &&
    // C5-AUTOFIELD: an automation column with no URL column to read is a column no run can
    // ever fill β€” the same "permanently blank column" the formula rule above refuses, so it
    // is refused here rather than created and then discovered.
    (kind !== "automation" || automationUrlField !== "") &&
    // ⭐ 2026-08-07 β€” both relational kinds are UNCREATABLE without their bag: `_clean_field`
    // returns None for a `link` with no target and a `rollup` with no link/function, so
    // creating one without this gate produces a column that is named, configured and simply
    // absent on the next read. The same "permanently blank column" argument as the two rules
    // above, one step worse β€” the column does not exist at all.
    (kind !== "link" || linkTable !== "") &&
    (kind !== "rollup" || (rollupMode === "source"
      // ⭐ 2026-08-09 β€” the read-through bag. ALL FOUR keys are required by `_clean_rollup`
      // (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
      // user forgets: without it the bag names a real measure grouped a real way with nothing
      // to match it to any row, and the field would be refused after Create.
      ? (rollupSource.topic !== "" && rollupSource.measure !== "" &&
         rollupSource.groupBy !== "" && rollupSource.on !== "")
      : (
        rollupLink !== "" &&
        (rollupFn === "countall" || rollupField !== "") &&
        // `latest` without an order is store order wearing a deterministic name.
        (rollupFn !== "latest" || rollupSortBy !== "")
      )));

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

  const create = () => {
    const clean = effectiveLabel.trim();
    if (!clean || !position || !canCreate) return;
    if (kind === "measure") {
      if (!chosenMeasure) return;
      onCreate(clean, chosenMeasure.type, position === "end" ? null : field.key, position,
               undefined, { key: chosenMeasure.key, window: measureWindow },
               withScope(undefined));
      onClose();
      return;
    }
    onCreate(clean, kind, position === "end" ? null : field.key, position,
             needsOptions(kind) ? options : undefined, undefined,
             withScope({
               ...extraFor(kind, formulaText, maxValue, codeLanguage),
               ...optionExtraFor(kind, createChoice.colors, createColorCode),
             }));
    onClose();
  };

  const canCreateSwap =
    swapToNewType != null &&
    swapLabel.trim() !== "" &&
    (!needsOptions(swapToNewType) || swapNewOptions.length > 0) &&
    (swapToNewType !== "formula" || swapFormulaCheck.ok);

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

  // ------------------------------------------------------- owner item 8: Edit-field dirties
  // ONE Save applies whatever changed β€” name, type, choices, stars, formula source β€” and it
  // must leave as ONE upsert when several changed together: sequential emits each read the
  // stale def and the second reverts the first (label rides extra.label / onFormula's label).
  const cleanRename = renameDraft.trim();
  // ⭐ 2026-08-09 β€” `onFieldConfig` is a SECOND door that can rename. `onRename` writes the
  // per-user overlay and is supplied for `custom_` fields only, so a pre-set Rollup β€” now
  // reconfigurable by owner ruling β€” had a configuration it could change and a name it could
  // not. Both ride the same PATCH; the label is part of the definition either way.
  const editNameDirty =
    (!!onRename || !!onFieldConfig) && cleanRename !== "" && cleanRename !== field.label;
  const editOptionsChanged =
    needsOptions(editType) &&
    editOptions.join("\n") !== choiceOptions(field).join("\n");
  const editAppearanceChanged =
    needsOptions(editType) &&
    (editColorCode !== (field.colorCodeOptions !== false) ||
      optionAppearanceSignature(editOptions, editChoice.colors) !==
        optionAppearanceSignature(choiceOptions(field), field.optionColors));
  const editStarsChanged = editType === "rating" && retypeMaxValue !== ratingMax(field);
  /** The type half was touched: a different type, or the SAME type with edited choices/stars
   *  (the owner's named case β€” "change the list of the single selections"). */
  /** C5-AUTOFIELD β€” the automation config is a property of the column exactly as the choice
   *  list is, so a change to it makes the type half DIRTY and rides the same one upsert. */
  const editAutomationChanged =
    editType === "automation" &&
    field.type === "automation" &&
    (editAutomationKind !== (field.automation?.kind ?? AUTOMATION_KINDS[0].key) ||
      editAutomationUrlField !== (field.automation?.urlField ?? ""));
  const editRetypeTouched =
    onRetype != null &&
    (editType !== field.type || editOptionsChanged || editAppearanceChanged ||
      editStarsChanged || editAutomationChanged);
  const editRetypeValid =
    (!needsOptions(editType) || editOptions.length > 0) &&
    (editType !== "automation" || editAutomationUrlField !== "");
  const editFormulaCheck = useMemo(
    () =>
      editFormulaText.trim() === ""
        ? { ok: false, error: "Type a formula", refs: [] as string[] }
        : validateFormula(editFormulaText, knownKeys, formulaSources, field.key),
    [editFormulaText, knownKeys, formulaSources, field.key]
  );
  const editFormulaTouched =
    !!onFormula &&
    field.type === "formula" &&
    editFormulaText.trim() !==
      (typeof field.formula === "string" ? field.formula.trim() : "");
  // A touched-but-invalid half BLOCKS the whole save β€” otherwise Save would apply the name
  // and silently drop the half-finished type change beside it.
  const editBlocked =
    (editRetypeTouched && !editRetypeValid) ||
    (editFormulaTouched && !editFormulaCheck.ok);
  // Item 21 (2026-08-02) β€” the PERIOD moved into this pane, so its dirty-check has to be
  // computed before the pane's save gate rather than beside the menu's own button. Same three
  // lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
  // initialiser is a TDZ crash at render, not a compile error.
  const currentWindow = field.measure ? normalizeWindow(field.measure.window) : null;
  const draftWindow = periodDraft ? normalizeWindow(periodDraft) : null;
  const periodChanged =
    draftWindow != null &&
    JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
  const canPeriod = !!field.measure && !!onPeriod;
  /**
   * ⭐⭐ 2026-08-09 β€” THE RELATIONAL EDIT: is this pane driving a `link`/`rollup` bag?
   *
   * β›” GATED ON `onFieldConfig`, which the host supplies for USER DATABASES ONLY. These bags live
   * in the table's shared definition (`PATCH /tables/{key}/fields/{key}`); there is no such door
   * on the Odoo-backed Customer/Product grids, so offering the editor there would be a form whose
   * Save has nowhere to go.
   */
  const editingRelational =
    !!onFieldConfig && (field.type === "rollup" || field.type === "link");
  const editRollupValid =
    field.type !== "rollup" ||
    (editRollup.source
      ? !!(editRollup.source.topic && editRollup.source.measure &&
           editRollup.source.groupBy && editRollup.source.on)
      : !!editRollup.link &&
        (editRollup.fn === "countall" || !!editRollup.field) &&
        (editRollup.fn !== "latest" || !!editRollup.sortBy));
  const editRelationalTouched =
    editingRelational &&
    (field.type === "rollup"
      ? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
      : editLinkTable !== (field.link?.table ?? "") ||
        editLinkSingle !== (field.link?.single === true));
  const canSaveEdit =
    !editBlocked &&
    (editingRelational
      ? (editRollupValid && (editRelationalTouched || editNameDirty) &&
         (field.type !== "link" || editLinkTable !== ""))
      : (editNameDirty || editRetypeTouched || editFormulaTouched ||
         (canPeriod && periodChanged)));
  /**
   * Item 15 β€” the renames, by ROW IDENTITY. A row that kept its id and changed its label was
   * renamed; a row with an id nobody has seen is new; an id that is gone was deleted. Empty
   * labels are skipped (a row being cleared before it is retyped is not a rename to ""), and a
   * rename to a label that already existed is skipped too β€” that is a MERGE, and merging two
   * choices into one is a different operation from renaming, with a different answer for the
   * cells that held either.
   */
  const optionRenames = (): { from: string; to: string }[] =>
    // A field that was not a choice field before has no values to migrate, and one being
    // retyped AWAY from choices is a different question (its cells stop being options at all).
    needsOptions(editType) && needsOptions(field.type)
      ? choiceRenames(editOptionDrafts, editOptionOrigin.current, choiceOptions(field))
      : [];
  const applyEdit = () => {
    if (!canSaveEdit) return;
    if (editingRelational && onFieldConfig) {
      // β›” THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives β€”
      // it does not merge with the stored bag β€” so a partial patch is a REBUILD, and an omitted
      // `limit` would silently become "no limit" rather than "unchanged".
      onFieldConfig({
        ...(editNameDirty ? { label: cleanRename } : {}),
        ...(field.type === "rollup"
          ? { rollup: editRollup as Record<string, unknown> }
          : { link: { table: editLinkTable,
                      ...(editLinkSingle ? { single: true } : {}) } }),
      });
      onClose();
      return;
    }
    if (editRetypeTouched && onRetype) {
      const renames = optionRenames();
      onRetype(
        editType,
        needsOptions(editType) ? editOptions : undefined,
        {
          ...(renames.length ? { renames } : {}),
          ...(editType === "rating" ? { max: retypeMaxValue } : {}),
          // ⭐ Wave-27 item 13 (R13) β€” always sent for a code column, `plain` included: the
          // host clears the key on plain, so this is what makes the picker reversible.
          ...(editType === "code" ? { code: { language: editCodeLanguage } } : {}),
          ...(needsOptions(editType)
            ? {
                colorCodeOptions: editColorCode,
                ...(Object.keys(editChoice.colors).length
                  ? { optionColors: editChoice.colors }
                  : {}),
              }
            : {}),
          ...(editType === "automation"
            ? {
                automation: {
                  kind: editAutomationKind,
                  source: "record_url_field" as const,
                  urlField: editAutomationUrlField,
                },
              }
            : {}),
          ...(editNameDirty ? { label: cleanRename } : {}),
        }
      );
    } else if (editFormulaTouched && onFormula) {
      onFormula(editFormulaText.trim(), editNameDirty ? cleanRename : undefined);
    } else if (editNameDirty && onRename) {
      onRename(cleanRename);
    }
    // Item 21 β€” the period is an INDEPENDENT property of a measure column, not a branch of
    // the identity edit, so it applies ALONGSIDE whatever the chain above did rather than
    // instead of it: renaming "Sales YTD" to "Sales" and re-pointing it at the last 90 days
    // is one edit to the user and must not silently drop half of itself.
    if (canPeriod && periodChanged && draftWindow) onPeriod!(draftWindow);
    onClose();
  };

  /**
   * Fields this column can be CHANGED to, split per wave-2 item 5: the "Pre-set fields" group
   * (the shared contract's predicate, `source === 'odoo' && !custom`) versus "Your fields" β€”
   * the overlay stratum and user-created columns. Hidden fields included in both: "change this
   * to Notes" is the whole point, and swapping BACK to a hidden custom field is the documented
   * restore path. The locked primary column cannot be swapped.
   */
  const swapOptions = fields.filter((f) => f.key !== field.key);
  const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
  const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));

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

  /** Wave-5 item 10 β€” which format editor this field gets, if any. */
  const formatKind: "number" | "date" | null =
    field.type === "int" || field.type === "currency" || field.type === "formula" ||
    field.type === "pct" || field.type === "rollup"
      ? "number"
      : field.type === "date" || field.type === "created_time"
        ? "date"
        : null;

  /**
   * Item 6 β€” Insert left/right (and Add at end) jump STRAIGHT to the create form: name + type
   * autofocused, and none of the note/change-field/other-column chrome rendered around it.
   */
  if (position) {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={
          position === "end" ? "Add field" : `Insert field ${position} of ${field.label}`
        }
        // The SAME selector as the full-menu branch, so React reconciling the two states does
        // not re-run the overlay's focus effect (its deps see one constant) β€” which would steal
        // focus to the first button a frame after the name input autofocused.
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead
          title={
            position === "end"
              ? "Add field"
              : position === "left"
                ? "Insert field left"
                : "Insert field right"
          }
          sub={position === "end" ? "Added as the last column" : `Next to ${field.label}`}
          onClose={onClose}
        />
        <div className="cg-column-create">
          <label>
            <span>Name</span>
            <input
              className="cg-input"
              autoFocus
              data-overlay-autofocus
              value={effectiveLabel}
              onChange={(event) => {
                setLabel(event.target.value);
                setLabelTouched(true);
              }}
              onKeyDown={(event) => event.key === "Enter" && create()}
            />
          </label>
          <div className="cg-type-block">
            <span className="cg-type-title">Field type</span>
            {/* Owner item 8 (2026-07-31): every type wears its own mark β€” the same TYPE_SHAPES
                glyph its column header wears. A native <option> cannot hold an SVG (the ruling
                iconShapes.ts records), so the control is a find box over a listbox of real
                rows, Airtable-style. The measure row appears exactly when the host offers
                measures β€” the same availability rule as the filter's measure conditions. */}
            <TypePicker
              value={kind}
              onPick={setKind}
              offerMeasure={measures.length > 0}
            />
          </div>
          {kind === "measure" && (
            <>
              {/* C-NAME β€” the row asked "Measure"/"Choose a measure…", which named the
                  INTERNAL concept at the user. What the person is picking is the business
                  number ("Sales", "Gross margin"), so the label says that. */}
              <label>
                <span>Number</span>
                {/* Item 20 (C-FLDSEL) β€” "Choose a number…" was an `<option value="">` that
                    only rendered while nothing was chosen; it is the picker's PLACEHOLDER
                    now, so the prompt is a state of the control rather than a row of the
                    vocabulary that could be picked. */}
                <FieldSelectButton
                  ariaLabel="Number to summarise"
                  placeholder="Choose a number…"
                  value={chosenMeasure ? measureKey : undefined}
                  onChange={setMeasureKey}
                  fields={measures.map((m) => ({
                    key: m.key, label: m.label, type: "measure" as const,
                  }))}
                />
              </label>
              <label>
                <span>Period</span>
                <span className="cg-measure-window">
                  <WindowPicker window={measureWindow} onWindow={setMeasureWindow} />
                </span>
              </label>
              {/* The helper line now carries what the old label's parenthetical was doing β€”
                  "(over a period)" β€” plus an example, because "Metric" alone does not say
                  that the answer moves with the window above it. */}
              <div className="cg-field-hint">
                A total, average or count over the period you choose β€” e.g. Sales, last 90
                days. Computed for every customer, and read-only.
              </div>
            </>
          )}
          <ExtraTypeEditor
            kind={kind}
            fields={fields}
            formulaText={formulaText}
            onFormulaText={setFormulaText}
            formulaError={formulaCheck.ok ? null : formulaCheck.error ?? null}
            maxValue={maxValue}
            onMaxValue={setMaxValue}
            codeLanguage={codeLanguage}
            onCodeLanguage={setCodeLanguage}
            idPrefix="cg-create"
            automationKind={automationKind}
            onAutomationKind={setAutomationKind}
            automationUrlField={automationUrlField}
            onAutomationUrlField={setAutomationUrlField}
            linkTargets={linkTargets}
            linkTable={linkTable}
            onLinkTable={setLinkTable}
            linkSingle={linkSingle}
            onLinkSingle={setLinkSingle}
            rollupMode={rollupMode}
            onRollupMode={setRollupMode}
            rollupSourceOffer={rollupSourceOffer}
            rollupSource={rollupSource}
            onRollupSource={setRollupSource}
            rollupLink={rollupLink}
            onRollupLink={(value) => {
              setRollupLink(value);
              setRollupField("");
              setRollupSortBy("");
              setRollupDistinctBy("");
              // Every condition names a column of the OLD target, so both lists are cleared for
              // the same reason: a leaf pointing at a field the new table does not have is a
              // filter that can only ever match nothing.
              setRollupWhere([]);
              setRollupConditions([]);
            }}
            rollupField={rollupField}
            onRollupField={setRollupField}
            rollupFn={rollupFn}
            onRollupFn={setRollupFn}
            rollupLimit={rollupLimit}
            onRollupLimit={setRollupLimit}
            rollupSortBy={rollupSortBy}
            onRollupSortBy={setRollupSortBy}
            rollupDistinctBy={rollupDistinctBy}
            onRollupDistinctBy={setRollupDistinctBy}
            rollupWhere={rollupWhere}
            onRollupWhere={setRollupWhere}
            rollupWhereConj={rollupWhereConj}
            onRollupWhereConj={setRollupWhereConj}
            rollupConditions={rollupConditions}
            onRollupConditions={setRollupConditions}
            rollupConditionConj={rollupConditionConj}
            onRollupConditionConj={setRollupConditionConj}
          />
          {needsOptions(kind) && (
            <OptionsEditor
              idPrefix="cg-create-option"
              drafts={createOptionDrafts}
              onDrafts={setCreateOptionDrafts}
              colorCode={createColorCode}
              onColorCode={setCreateColorCode}
              type={kind}
            />
          )}
          {kind === "user" && (
            <div className="cg-field-hint">
              {userOptions.length
                ? `${userOptions.length} people can be assigned, from your user list.`
                : "No user list yet, so there is no one to assign."}
            </div>
          )}
          {scopeChoice && <ScopeControl value={scopeDraft} onValue={setScopeDraft} />}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={!canCreate}
              onClick={create}
            >
              Create field
            </button>
            <button
              type="button"
              className="cg-btn"
              // Opened straight into the form (the header "+")? Cancel means close β€”
              // there is no action list behind it to fall back to.
              onClick={() => (initialPosition ? onClose() : setPosition(null))}
            >
              Cancel
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------ EDIT FIELD pane (item 8)
  // Owner item 8 (2026-07-31): ONE window owning the field's identity β€” name, type (with the
  // per-type choices/stars/formula editors), and the Change-field control. Absorbs the former
  // Rename and Change-field panes.
  if (pane === "edit") {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Edit field ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Edit field" sub={typeLine} onClose={onClose} />
        <div className="cg-column-create">
          {onRename || editingRelational ? (
            <label>
              <span>Name</span>
              <input
                className="cg-input"
                autoFocus
                data-overlay-autofocus
                value={renameDraft}
                onChange={(event) => setRenameDraft(event.target.value)}
                onKeyDown={(event) => event.key === "Enter" && applyEdit()}
              />
            </label>
          ) : (
            <label>
              <span>Name</span>
              <input
                className="cg-input"
                value={field.label}
                disabled
                aria-label="Field name (read-only)"
              />
              <span className="cg-field-hint">
                A source field keeps its name and type from the data source.
              </span>
            </label>
          )}
          {/* C5-AUTOFIELD β€” an EXISTING automation column edits its CONFIG, not its type.
              ⚠ This guard is load-bearing, not tidiness. `automation` is excluded from
              RETYPE_TYPES (see its note), so rendering the picker for one would show a
              listbox whose current value is not among its options β€” the failure recorded in
              [[cg-condition-builder-items]], where a control missing its own value silently
              presents the FIRST option as if it were the selection. One Save later the column
              is a different type and its statuses are editable text. */}
          {/*
            ⭐⭐ 2026-08-09 (owner) β€” AN EXISTING ROLLUP/LINK EDITS ITS CONFIGURATION HERE.

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

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

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

  // ------------------------------------------------------------------ NOTE pane (item 2)
  // "Edit field description" edits the USER's note β€” the canonical `description` is the
  // contract's default and is shown as context, never written from here.
  if (pane === "note") {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Edit description for ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Edit field description" sub={field.label} onClose={onClose} />
        <div className="cg-column-create">
          {field.description && (
            <div className="cg-field-hint cg-desc-default">
              Default description: {field.description}
            </div>
          )}
          <label>
            <span>Your description</span>
            <textarea
              className="cg-input"
              data-overlay-autofocus
              autoFocus
              rows={4}
              value={note}
              placeholder={
                field.description
                  ? "Write your own to replace the default…"
                  : "Explain how this field should be used…"
              }
              onChange={(event) => setNote(event.target.value)}
            />
          </label>
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={note === (field.note ?? "")}
              onClick={() => {
                onNote(note);
                onClose();
              }}
            >
              Save
            </button>
            <button type="button" className="cg-btn" onClick={() => setPane("menu")}>
              Back
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------- PERMISSIONS pane (item 1)
  if (pane === "permissions") {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Edit permissions for ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Edit field permissions" sub={field.label} onClose={onClose} />
        <div className="cg-column-create">
          <div className="cg-field-hint">
            Who can edit this field's values{field.createdBy ? ` (created by ${field.createdBy})` : ""}.
          </div>
          {(
            [
              ["everyone", "Everyone"],
              ["creator", "Only the creator"],
              ["admins", "Only admins"],
            ] as const
          ).map(([value, text]) => (
            <label key={value} className="cg-radio-row">
              <input
                type="radio"
                name="cg-perm"
                data-overlay-autofocus={value === "everyone" ? true : undefined}
                checked={permDraft === value}
                onChange={() => setPermDraft(value)}
              />
              <span>{text}</span>
            </label>
          ))}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={permDraft === (field.permissions?.edit ?? "everyone")}
              onClick={() => {
                onPermissions?.(permDraft);
                onClose();
              }}
            >
              Save
            </button>
            <button type="button" className="cg-btn" onClick={() => setPane("menu")}>
              Back
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------------ FORMAT pane (item 10)
  /**
   * ⭐⭐ WAVE-29 T33 (owner item 17) β€” THE COLUMN SUMMARY PANE.
   *
   * A flat list of the six aggregates plus "None", because that is the whole decision β€” there is
   * no draft to reconcile and no Save button to press, so the click IS the answer and the pane
   * closes on it (the same shape as Sort, one group up, and unlike Format, which composes four
   * settings into one bag).
   *
   * β›” THE OPTIONS COME FROM `aggOptions`, never from a list written here. `sum Β· average Β·
   * median Β· min Β· max` are numeric-only and `count` counts ROWS, so a text column offers exactly
   * one row β€” and it offers it, rather than hiding the pane, because "how many records is this
   * group" is the summary a text column CAN answer.
   */
  if (pane === "summary" && onAggregate) {
    const options = aggOptions(field);
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Summarize ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Summarize" sub={field.label} onClose={onClose} />
        <div className="cg-menu-list" role="none">
          <button
            type="button"
            data-overlay-autofocus={field.agg ? undefined : true}
            aria-pressed={!field.agg}
            onClick={() => {
              onAggregate(undefined);
              onClose();
            }}
          >
            <MenuLabel icon="off" text="None" />
          </button>
          {options.map((name) => (
            <button
              key={name}
              type="button"
              data-overlay-autofocus={field.agg === name ? true : undefined}
              aria-pressed={field.agg === name}
              onClick={() => {
                onAggregate(name);
                onClose();
              }}
            >
              <MenuLabel icon="format" text={AGG_LABELS[name]} />
            </button>
          ))}
        </div>
      </AnchoredOverlay>
    );
  }

  if (pane === "format" && formatKind) {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Format ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Field format" sub={field.label} onClose={onClose} />
        <div className="cg-column-create">
          {formatKind === "number" ? (
            <>
              <label className="cg-radio-row">
                <input
                  type="checkbox"
                  data-overlay-autofocus
                  checked={fmtDraft.thousands !== false}
                  onChange={(e) =>
                    setFmtDraft((d) => ({ ...d, thousands: e.target.checked }))
                  }
                />
                <span>Thousands separator (12,345)</span>
              </label>
              <label>
                <span>Decimal places</span>
                <select
                  className="cg-select"
                  value={
                    Number.isInteger(fmtDraft.decimals) ? String(fmtDraft.decimals) : ""
                  }
                  aria-label="Decimal places"
                  onChange={(e) =>
                    setFmtDraft((d) => {
                      const next = { ...d };
                      if (e.target.value === "") delete next.decimals;
                      else next.decimals = Number(e.target.value);
                      return next;
                    })
                  }
                >
                  <option value="">As entered</option>
                  {[0, 1, 2, 3, 4].map((n) => (
                    <option key={n} value={n}>
                      {n}
                    </option>
                  ))}
                </select>
              </label>
              <label className="cg-radio-row">
                <input
                  type="checkbox"
                  checked={fmtDraft.abbrev === true}
                  onChange={(e) =>
                    setFmtDraft((d) => ({ ...d, abbrev: e.target.checked }))
                  }
                />
                <span>Abbreviate large numbers (34.0M)</span>
              </label>
            </>
          ) : (
            <>
              <label className="cg-radio-row">
                <input
                  type="checkbox"
                  data-overlay-autofocus
                  checked={fmtDraft.time ?? field.type === "created_time"}
                  onChange={(e) => setFmtDraft((d) => ({ ...d, time: e.target.checked }))}
                />
                <span>Include the time of day</span>
              </label>
              <label>
                <span>Time zone</span>
                <select
                  className="cg-select"
                  value={fmtDraft.tz === "utc" ? "utc" : "local"}
                  aria-label="Time zone"
                  onChange={(e) =>
                    setFmtDraft((d) => ({ ...d, tz: e.target.value as "local" | "utc" }))
                  }
                >
                  <option value="local">Your local time</option>
                  <option value="utc">UTC</option>
                </select>
              </label>
            </>
          )}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={JSON.stringify(fmtDraft) === JSON.stringify(field.format ?? {})}
              onClick={() => {
                onFormat?.(fmtDraft);
                onClose();
              }}
            >
              Save
            </button>
            <button type="button" className="cg-btn" onClick={() => setPane("menu")}>
              Back
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------------ the MENU pane
  // Wave-5 items 1/2/3: a flat action list. Editors open their OWN windows (the panes above);
  // nothing edits inline here. Conditional entries render IFF they apply to the current view.
  const canPermissions =
    !!onPermissions &&
    !!viewer &&
    (viewer.isAdmin || (field.createdBy != null && field.createdBy === viewer.name));

  return (
    <AnchoredOverlay
      anchor={state.anchor}
      className="cg-column-menu"
      onDismiss={onClose}
      role="dialog"
      ariaLabel={`Column settings for ${field.label}`}
      initialFocus="[data-overlay-autofocus]"
      dataKind="column-menu"
    >
      <PaneHead title={field.label} sub={typeLine} onClose={onClose} />

      {/* Item 8c β€” any measure-carrying column exposes its PERIOD, the property that defines
          it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
          is one line that STATES the period and opens that pane, because the window is the
          first thing you want to know about a metric column and the menu had become the only
          place it was written down. A row, not a control: the menu pane edits nothing inline. */}
      {canPeriod && !schemaLocked && (
        <button
          type="button"
          className="cg-column-periodline"
          onClick={() => {
            setRenameDraft(field.label);
            setPane("edit");
          }}
        >
          <span className="cg-swap-label">Period</span>
          <span className="cg-column-periodval">{windowLabel(field.measure!.window)}</span>
        </button>
      )}

      {/* Wave-7 item W4 (contract C6): Airtable's grouping, thin dividers between groups,
          an icon on EVERY action. Presentation only β€” every handler and event is the one it
          was before; entries not in Airtable's list slot into the nearest sensible group. */}
      <div className="cg-column-actions">
        {/* Owner item 8 (2026-07-31) β€” EDIT FIELD sits at the very top, above Duplicate:
            the one window for the field's name, type (with per-type choices/stars/formula)
            and the Change-field control. Offered on EVERY field β€” what a read-only field
            cannot change, the pane says honestly instead of hiding the door. */}
        {!schemaLocked && (
          <button type="button" data-overlay-autofocus onClick={() => {
            setRenameDraft(field.label);
            setPane("edit");
          }}>
            <MenuLabel icon="rename" text="Edit field" />
          </button>
        )}

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

        {/* Group 1 β€” Duplicate Β· Insert left Β· Insert right (+ Add at end, same family). */}
        {!schemaLocked && onDuplicate && (
          <button type="button" onClick={() => { onDuplicate(); onClose(); }}>
            <MenuLabel icon="duplicate" text="Duplicate field" />
          </button>
        )}
        <button type="button" onClick={() => setPosition("left")}>
          <MenuLabel icon="insertLeft" text="Insert field left" />
        </button>
        <button type="button" onClick={() => setPosition("right")}>
          <MenuLabel icon="insertRight" text="Insert field right" />
        </button>
        <button type="button" onClick={() => setPosition("end")}>
          <MenuLabel icon="addEnd" text="Add field at end" />
        </button>

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

        {/* Group 2 β€” the rest of the def-editing family: description Β· permissions Β· format.
            Rename and Change field live INSIDE Edit field now (owner item 8) β€” their old
            rows are gone, not duplicated. */}
        {!schemaLocked && (
          <button type="button" onClick={() => setPane("note")}>
            <MenuLabel icon="description" text="Edit field description" />
          </button>
        )}
        {!schemaLocked && canPermissions && (
          <button type="button" onClick={() => setPane("permissions")}>
            <MenuLabel icon="permissions" text="Edit field permissions" />
          </button>
        )}
        {!schemaLocked && formatKind && (
          <button type="button" onClick={() => setPane("format")}>
            <MenuLabel icon="format" text="Field format" />
          </button>
        )}
        {/* ⭐ WAVE-29 T33 (owner item 17) β€” the COLUMN SUMMARY. Offered on every column, because
            `count` applies to any type; the numeric folds are filtered per type inside the pane
            by `aggOptions`. ⚠ NOT gated on `schemaLocked`: a summary is a reading of the column,
            not a change to its schema, so it belongs on a pre-set column too β€” the same reason
            Sort and Filter sit below without that gate. */}
        {onAggregate && (
          <button type="button" onClick={() => setPane("summary")}>
            <MenuLabel
              icon="format"
              text={field.agg ? `Summary: ${AGG_LABELS[field.agg]}` : "Summarize this column"}
            />
          </button>
        )}

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

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

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

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

        {/* Group 5 β€” hide Β· delete. */}
        <button
          type="button"
          disabled={locked}
          title={locked ? "The primary field stays visible" : undefined}
          onClick={onHide}
        >
          <MenuLabel icon="hide" text="Hide field" />
        </button>
        {!schemaLocked && onDelete && (
          <button
            type="button"
            className="is-danger"
            title={
              /**
               * ⭐ 2026-08-10 β€” THE PRE-SET ROLLUP COMES BACK, and the honest place to say so is
               * here rather than in a tombstone.
               *
               * A pre-set column carries `automation.preset`, and BOTH reconcilers
               * (`_reconcile_ig_graph_fields`, `odoo_relational`'s forward migration) re-declare
               * every field they own on the next run. RECONFIGURING one sticks β€” the custody
               * stamp (`userEdited`) switches the reconciler off for that column β€” but DELETING
               * one leaves nothing behind to carry a stamp, so it is re-added within a tick.
               * β›” NOT FIXED WITH A TOMBSTONE, deliberately: that is a new store key two
               * reconcilers must both consult, and the custody stamp is the precedent for how
               * that goes wrong when only one of them reads it. The delete is not broken β€” it is
               * a delete of something the product re-declares, and the user is told which.
               */
              field.measure
                ? "Removes this formula column from the workspace."
                : field.automation?.preset === true
                ? "Part of this database's built-in schema β€” it will be re-created on the " +
                  "next run. Hide it to keep it off the grid."
                : field.type === "rollup" || field.type === "link" ||
                  field.type === "formula"
                ? "Removes this column. No values are lost β€” it holds none of its own."
                : "Removes this field AND its values on every row."
            }
            onClick={() => (confirmDelete ? onDelete() : setConfirmDelete(true))}
          >
            <MenuLabel
              icon="trash"
              text={confirmDelete ? "Delete permanently?" : "Delete field"}
            />
          </button>
        )}
      </div>
    </AnchoredOverlay>
  );
}