File size: 177,434 Bytes
9b857f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------
// automation/AutomationBuilder.tsx β€” the BUILDER (owner item 3b, contracts
// C1/C2/C4, ruling R1: "exact layout, Loopable skin").
//
// THE ANATOMY IS AIRTABLE'S, 1:1, and it is the owner's reference (images 1-9):
// a centre column of TRIGGER β†’ ACTIONS with a spine down the left carrying each
// step's status chip, dashed add-boxes at the end of each section, and a
// Properties panel on the right whose sections are Trigger details /
// Configuration / Test step. Every colour, size and weight is OURS (R1,
// DESIGN.md) β€” no Airtable blue, no caps micro-labels (R6: "TRIGGER" is
// "Trigger" here, and de-capping takes the letter-spacing with it).
//
// β›” IT RENDERS SYNCHRONOUSLY FROM WHAT IT WAS HANDED (C14 leg 1). No fetch, no
// effect, no second frame: the trigger comes from `automation.trigger`, the
// actions from `automation.flow`, the machine steps from `automation.graph` β€”
// all three already on the list payload the rail used to draw the row you
// clicked. THIS IS THE GHOST FIX. The old detail rendered Steps, then swapped to
// the Board when `/board` answered, so switching automations painted the
// PREVIOUS one's shape inside the new one's frame for as long as a fetch takes.
// A view that cannot be in two shapes cannot show you the wrong one.
//
// β›” NO CLIENT UNION OVER A SERVER VOCABULARY, anywhere. Trigger keys, action
// kinds, comparison operators, ending modes, review deciders and every ceiling
// ride `GET /automations`. What this file owns is pixels and wording.
//
// WHAT PERSISTS WHEN. A discrete choice writes immediately β€” picking a trigger,
// adding an action, flipping a switch β€” because a control you have to remember
// to Save is not a control (R9). FREE TEXT does not: a value, a prompt or a name
// commits on BLUR, or every keystroke would PATCH a half-typed condition and the
// server would refuse most of them out loud (the cron-string precedent in
// AutomationTrigger).
// ---------------------------------------------------------------------------
import type { ReactNode } from "react";
import { useEffect, useRef, useState } from "react";

// ⭐ WAVE 30 Β· ITEM 7 (R3 + R4) β€” connector identity, from the ONE module that owns it. Not a
// second copy of two SVGs: the directory, this menu and the trigger picker all answer "which
// company is this row about", and three answers is how a platform gets added in two of them.
import { brandForConnector, brandForKind, hasBrandKind } from "../connectors/brandMarks";

import type {
  Action,
  ActionCatalogRow,
  Automation,
  Cond,
  FlowVocab,
  GraphNode,
  OAuthStatus,
  TriggerOption,
  UserTable,
} from "./automationApi";
// ⭐ WAVE 26 Β· ITEM 22 / D-70 β€” the Run guard, imported rather than re-derived. This file and
// `AutomationDetail` each paint a Run button onto the same paid action; ONE function decides.
// ITEM 9 / R11 β€” `createTable` + `AutomationError` for the in-place "+ New database".
import { AutomationError, createTable, runBlock } from "./automationApi";
import CondBuilder, { condComplete } from "./CondBuilder";
import { groupActions, groupBranches, groupByPanel, numberActions, reorderList }
  from "./steps";
// ⭐ WAVE 25 item 5b (C2) β€” the grouped picker, and `TriggerMark` with it. The icon vocabulary
// MOVED to that file rather than being copied into it: the whole of item 5b is that the compact
// control in Properties and the big "+ Add trigger" menu are one control, and two copies of the
// marks is how they drift back into looking like two features.
import PresetPlan from "./PresetPlan";
import TriggerPicker, { TriggerMark } from "./TriggerPicker";

/**
 * β›” A PRIVATE MIME, AND `text/plain` IS NEVER SET (owner item 11; the wave-13 C-LAYOUT scar).
 * A drag carrying `text/plain` is a drag the whole operating system understands: drop it on any
 * input, textarea or contenteditable β€” this builder is full of them β€” and the browser TYPES the
 * payload in, so a mis-aimed reorder silently writes an action id into somebody's condition
 * value. A private type is inert everywhere except the drop targets below, which is why the nav
 * rail's own drag uses one (`Shell.tsx:90 NAV_DRAG_TYPE`).
 * ⚠ The board's card drag still uses `text/plain` (`AutomationBoard.tsx:167`) β€” noted, not fixed
 * here: that file belongs to another session this wave.
 */
const ACTION_DRAG_TYPE = "application/x-loopable-action";

interface Props {
  automation: Automation;
  /**
   * THE AUTOMATION'S NAME (item 15b, C-DETAIL) β€” it left the page header and Properties is where
   * it went, at the top, above whatever step is selected. REQUIRED, all three: an optional prop
   * degrades to "the field does not exist", which looks exactly like never having built it.
   *
   * ⚠ TEXT AND COMMIT ARE SEPARATE ON PURPOSE. This is the cron field's shape
   * (`AutomationTrigger`'s `onCronText` / `onSchedule`): free text stays controlled while typing
   * and writes ONCE on blur, because per-keystroke would PATCH a half-typed name. Folding them
   * into one callback would force a choice between a laggy controlled input and a save per
   * keystroke, and this file has already paid for both.
   */
  name: string;
  onNameText: (v: string) => void;
  onNameCommit: () => void;
  /** The server's trigger vocabulary (C3). Absent is a state this file states, never fills in. */
  triggers?: TriggerOption[];
  catalog: ActionCatalogRow[];
  vocab?: FlowVocab;
  tables: UserTable[];
  oauth: OAuthStatus | null;
  /** True while a write is in flight β€” drives the "All changes saved" stamp and disables edits. */
  busy: boolean;
  /** Write a partial definition. The caller owns the request and prints the refusal verbatim. */
  onPatch: (body: Record<string, unknown>) => void;
  onToggleNode: (nodeId: string) => void;
  /**
   * β›” CHOOSING A TRIGGER IS NOT A `{trigger:{key}}` PATCH, and getting that wrong is invisible.
   * `schedule` is what today's engine actually READS, so a pick has to write BOTH halves or
   * "At a scheduled time" would store a key and leave the cron switched off β€” a trigger that
   * says it is scheduled and never fires. The detail already owns that two-write shape
   * (`pickTrigger`); the builder calls it rather than composing a second copy of it.
   */
  onPickTrigger: (key: string) => void;
  onRunNow: () => void;
  /**
   * The MACHINE steps' config bodies (source / columns / capture / find / write). They live in
   * `AutomationDetail`, so they are passed IN rather than moved: a builder that re-implemented
   * them would be a second copy of five panels whose only job is to agree with the engine.
   *
   * ⚠ IT TAKES A PANEL KEY, NOT A NODE (item 5, C-CFG). It used to be
   * `(node: GraphNode) => ReactNode`, and the caller's whole body was `panelBody(node.panel)` β€”
   * so the node was only ever a wrapper around the key. Now that Properties renders the panels
   * GROUPED BY that key, taking a node would invite the caller to pass one node of a group and
   * quietly imply the body belongs to it alone.
   */
  renderNodeBody: (panel: string) => ReactNode;
  /**
   * The SCHEDULE half of the trigger face (`AutomationTrigger` with its picker hidden). Passed
   * in for the same reason the node panels are: the cron round-trip, the server's preset list
   * and the tick-honesty note exist exactly once, and both this view and the board render the
   * same element rather than two copies of three things that go wrong invisibly.
   */
  scheduleFace: ReactNode;
  /**
   * ⭐ WAVE 27 Β· CONTRACT C11 β€” is the PROPERTIES panel the one on screen?
   *
   * β›” THE STATE LIVES IN `AutomationDetail`, NEVER HERE, and the contract says so for a
   * structural reason: the two panels that share this column are children of DIFFERENT
   * components β€” Properties is this file's, the Run log is `AutomationDetail`'s β€” so the only
   * place that can know "exactly one is visible" is their common parent. A local boolean here
   * could hide Properties while the log was also hidden, or show both.
   * ⚠ REQUIRED. An optional flag defaulting to `true` would make an unmounted toggle look like
   * a working panel, which is the shape this repo keeps paying for.
   */
  showProperties: boolean;
  /** The Properties/Run-history switch, OWNED by `AutomationDetail` and drawn in both panel
   *  heads so it is in the same place whichever one is showing. */
  panelTabs: ReactNode;
  /** Announce that a step (or the trigger) was clicked, so the parent can bring Properties
   *  forward β€” C11's "clicking any step card switches to Properties". */
  onStepPicked: () => void;
  /**
   * Does the cron drive the CURRENT trigger (owner item 7)? REQUIRED, and decided by the caller
   * for the reason `AutomationTrigger.schedules` gives: which keys the cron drives is a per-key
   * fact, and no component below the detail is entitled to name trigger keys.
   */
  schedules: boolean;
  /**
   * ⭐ THE DATABASE THE FLOW'S RECORDS WALK (owner item 12a) β€” the trigger's table, or the
   * automation's own target, resolved by the caller the way `automation_engine._flow_table` does.
   * REQUIRED: an absent one degrades to an empty field list, which is the exact defect this prop
   * exists to fix and is indistinguishable from "this database has no columns".
   */
  walkTable: string;
  /**
   * ⭐ WAVE 26 Β· ITEM 9 / R11 β€” RE-READ THE DATABASE LIST, after an action's picker created one.
   *
   * β›” REQUIRED, deliberately. The wave doc's rule is "prefer a REQUIRED prop; an optional one
   * degrades silently to 'the feature does not exist'" β€” and here the silent degradation has a
   * particularly bad shape: the database really would be created, on the server, and simply not
   * appear in the picker that made it. The user then makes a second one with the same name
   * (duplicate names are legal), and the automation still points at neither.
   */
  onTablesChanged: () => Promise<void> | void;
  /**
   * Is there an edit the HEADER's Save still owns? REQUIRED, and it exists so the panel's
   * "All changes saved" stamp can stop being a claim about fields it does not cover β€” the
   * machine steps' panels moved into Properties this wave and they commit with Save, not on
   * change.
   */
  dirty: boolean;
}

/*
 * ⚠ `"node"` LEFT THIS UNION WITH THE MACHINE CARDS (item 5). It existed so a click on one of
 * those cards could open its panel; with the cards gone nothing can set it, and a variant no
 * code path can reach is a branch that reads as supported and is not.
 */
type Sel = { kind: "trigger" | "action"; id: string };

/** Airtable phrases the empty state's shortcuts; ours come from the SERVER's own list (image 1). */
const SUGGESTED = 6;

/**
 * ⭐⭐ WAVE 30 Β· W30-T23 / C3 β€” THE ENRICH KINDS, MIRRORING `automation_engine.ENRICH_KINDS`.
 *
 * β›” ONE PREDICATE, TWO CALL SITES, and both had to move or the ticket would have half-shipped:
 * `seedFor` decides whether the menu row can be ADDED at all, and the properties panel decides
 * whether the added step has any CONTROLS. Widening only the first yields a step a person can add
 * and cannot configure; widening only the second yields a panel for a row that is permanently
 * faded. D-79 was that pair coming apart on the Instagram side.
 * ⚠ Named as a list rather than written twice, because the server's own validator branches on a
 * TUPLE of the same two names β€” a third platform must be one edit here, not a grep.
 */
const ENRICH_KINDS = ["enrich_instagram", "enrich_tiktok"];
const isEnrich = (kind: string): boolean => ENRICH_KINDS.includes(kind);

/**
 * ⭐⭐ WAVE 33 Β· W33-T52 (owner item 16: *"real configuration under Web Action"*) β€” THE FIVE WEB
 * KINDS, and the SHAPE of each one's config, in ONE table read by BOTH halves.
 *
 * β›” THE PAIR THE COMMENT ABOVE WARNS ABOUT HAD ALREADY COME APART HERE, in the worse direction.
 * `seedFor` gained all five branches at wave 31 QA, so every web action could be ADDED β€” and
 * `ActionProps` never gained an arm, so none of them could be CONFIGURED. The step landed on the
 * canvas with a blank config, the panel painted a heading and nothing else, and the runner blocked
 * it at run time with a sentence naming keys no surface let anybody type. Five whole, correct,
 * unusable actions: `web_*` appeared in this entire client exactly once, in a comment.
 * ⚠ SO THE KEYS ARE DECLARED ONCE. The seed and the panel read the same object β€” the seed spreads
 * it, the panel walks its keys IN ORDER to decide which controls to draw β€” because a second
 * per-kind key list is precisely how the two halves diverged the first time
 * ([[constant-two-features-share]]).
 * β›” EVERY KEY HERE SURVIVES `_clean_action_config`, and that is not a coincidence to be kept by
 * memory: the server's web arm is an ALLOWLIST, so a key this table invents is dropped on save β€”
 * the panel would accept a value, the local state would keep it, and it would be gone on reload.
 * `verify_automation_ui` pins this table against the server's own allowlist for that reason.
 * ⚠ Which keys are REQUIRED is deliberately NOT here β€” it rides the wire from `ACTION_REQUIRED`
 * (`FlowVocab.actionRequired`), so the red mark and the runner's refusal cannot disagree.
 */
const WEB_KINDS = ["web_goto", "web_read", "web_click", "web_fill", "web_repair"];
const isWeb = (kind: string): boolean => WEB_KINDS.includes(kind);
const WEB_SEEDS: Record<string, Record<string, unknown>> = {
  web_goto: { url: "", waitFor: "", timeoutMs: 20000 },
  web_read: { url: "", selector: "", field: "", attr: "text", all: false, waitFor: "",
              timeoutMs: 20000 },
  web_click: { url: "", selector: "", waitFor: "", dryRun: false, timeoutMs: 20000 },
  web_fill: { url: "", selector: "", value: "", secret: false, waitFor: "", dryRun: false,
              timeoutMs: 20000 },
  web_repair: { url: "", selector: "", hint: "", waitFor: "", timeoutMs: 20000 },
};
/**
 * ⚠ `waitFor` AND `dryRun` WERE REACHABLE FROM THE RUNNER AND FROM NOWHERE ELSE, and they were
 * found by the verifier that checked this ticket rather than by anything in it. The engine keeps
 * both on every web kind and the job acts on them β€” `waitFor` on all five (`_after` waits for a
 * selector once the action is done), `dryRun` on `web_fill` and `web_click` ONLY, where the job
 * resolves the element and reports what it WOULD have typed or clicked instead of doing it.
 * β›” SO `dryRun` IS SEEDED ON EXACTLY THOSE TWO. Offering it on `web_read` would paint a control
 * that changes nothing, which is the same defect as a missing one wearing better clothes
 * [[wrong-parent-not-broken-control]].
 */

/** The server's clamp on `timeoutMs`, mirrored so the BOX and the STORE cannot disagree. */
const WEB_TIMEOUT_MIN = 1000;
const WEB_TIMEOUT_MAX = 120000;

/**
 * ⭐⭐ WAVE 33 Β· W33-T56 (owner item 7, ruling R3) β€” THE FUZZY STEP'S OWN SHAPE.
 *
 * β›” IT IS NOT A `web_*` KIND AND MUST NOT BE ADDED TO `WEB_KINDS`. That list is held name-for-name
 * against the server's own tuple by a gate, and against the RUNNER's three copies of it; widening
 * it here to get a free seed would put `ai_agent` into a set the browser job's runner does not
 * implement. It is a sibling, so it gets a sibling's entry.
 * β›” AND IT NEEDS BOTH HALVES, TODAY, for the reason this file learned twice in one wave: a kind
 * with a catalog row and no SEED is permanently unclickable (D-79), and a kind with a seed and no
 * PANEL is addable and unconfigurable (W33-T52, the five web actions). Two out of three ships an
 * invisible feature; three out of three is the only number that is a feature.
 * ⚠ NO `selector`. Working the selector out is the whole step β€” a selector box here would be a
 * control that contradicts the action's reason to exist.
 */
const AI_AGENT_SEED: Record<string, unknown> = {
  url: "", instruction: "", field: "", maxSteps: 6, dryRun: false, timeoutMs: 20000,
};
/** The server's own ceiling on how many steps one fuzzy instruction may compose. */
const AI_AGENT_MAX_STEPS = 12;

/* β›” `TriggerMark` STOOD HERE AND MOVED TO `TriggerPicker.tsx` (wave 25 item 5b, C2).
   It is IMPORTED back for the trigger card below. Moving rather than copying is the point of
   the item: the compact control in Properties and this menu are one picker now, and the marks
   are the thing the owner noticed missing from one of them (reference/ERROR 3.png). */
function ActionMark({ kind }: { kind: string }) {
  /* ⭐⭐ WAVE 30 Β· ITEM 7 / R4 β€” the same one-line resolution `TriggerMark` carries, and for the
     same reason: this component is drawn in the add-action menu, on every step card and on every
     machine node, so a connected action must wear its company's logo in all three or it wears two
     identities on one screen. Unbranded kinds fall through to the house glyphs below, untouched. */
  const brand = brandForKind(kind);
  if (brand) return brand;
  const common = {
    width: 15, height: 15, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor",
    strokeWidth: 1.4, strokeLinecap: "round" as const, strokeLinejoin: "round" as const,
    "aria-hidden": true,
  };
  if (kind === "group")
    return (
      <svg {...common}>
        <path d="M2.6 8h3l2.6-3.6h5M8.2 11.6H5.6m2.6 0h5" />
        <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
      </svg>
    );
  if (kind === "create_record")
    return (
      <svg {...common}>
        <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="2" />
        <path d="M8 5.6v4.8M5.6 8h4.8" />
      </svg>
    );
  if (kind === "find_records")
    return (
      <svg {...common}>
        <circle cx="7.2" cy="7.2" r="4" />
        <path d="m10.2 10.2 3.2 3.2" />
      </svg>
    );
  /*
    ⚠ THE MACHINE KINDS ARE HERE TOO, and leaving them out was a real defect for one render:
    the engine's nodes are `source | capture | branch | write`, none of which matched above, so
    "Write to the database" and "Fetch the page" both drew the PENCIL β€” an edit glyph on a step
    that reads a web page and a step that writes a database. Caught by reading the screenshot,
    not by a gate ([[ui-invisible-to-assertions]]): the icon was present, legible and wrong.
    These are the shapes the retired `AutomationSteps.KindMark` used, kept with their meanings.
  */
  if (kind === "source")
    return (
      <svg {...common}>
        <circle cx="8" cy="8" r="5.6" />
        <path d="M2.6 8h10.8M8 2.4c1.5 1.7 2.2 3.6 2.2 5.6S9.5 12.3 8 13.6C6.5 12.3 5.8 10 5.8 8s.7-3.9 2.2-5.6z" />
      </svg>
    );
  if (kind === "write")
    return (
      <svg {...common}>
        <ellipse cx="8" cy="4.2" rx="4.8" ry="1.9" />
        <path d="M3.2 4.2v7.6c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9V4.2M3.2 8c0 1 2.1 1.9 4.8 1.9s4.8-.9 4.8-1.9" />
      </svg>
    );
  if (kind === "capture")
    return (
      <svg {...common}>
        <path d="M8 2.6v7.2M5.2 7l2.8 2.8L10.8 7M3 12.4h10" />
      </svg>
    );
  if (kind === "branch")
    return (
      <svg {...common}>
        <path d="M2.6 8h3.2l2.6-3.6h5M8.4 11.6H5.8m2.6 0h5" />
        <path d="M11.6 2.6 13.4 4.4 11.6 6.2M11.6 9.8l1.8 1.8-1.8 1.8" />
      </svg>
    );
  if (kind === "update_record")
    return (
      <svg {...common}>
        <path d="M11.4 2.8 13.2 4.6 6 11.8l-2.6.8.8-2.6z" />
        <path d="M3 13.6h10" />
      </svg>
    );
  if (kind === "send_email")
    return (
      <svg {...common}>
        <rect x="2.2" y="3.6" width="11.6" height="8.8" rx="1.6" />
        <path d="m2.6 4.6 5.4 3.8 5.4-3.8" />
      </svg>
    );
  if (kind === "slack")
    return (
      <svg {...common}>
        <path d="M13.4 9.4a1.6 1.6 0 0 1-1.6 1.6H5.4L2.6 13.4V4.2a1.6 1.6 0 0 1 1.6-1.6h7.6a1.6 1.6 0 0 1 1.6 1.6z" />
      </svg>
    );
  if (kind === "run_script")
    return (
      <svg {...common}>
        <path d="M5.6 5.4 3 8l2.6 2.6M10.4 5.4 13 8l-2.6 2.6M9 3.4 7 12.6" />
      </svg>
    );
  if (kind === "generate_ai")
    return (
      <svg {...common}>
        <path d="M8 2.4l1.5 3.4 3.4 1.5-3.4 1.5L8 12.2 6.5 8.8 3.1 7.3l3.4-1.5z" />
      </svg>
    );
  if (kind === "repeating_group")
    return (
      <svg {...common}>
        <path d="M3 8a5 5 0 0 1 5-5c2 0 3.4 1 4.3 2.4M13 8a5 5 0 0 1-5 5c-2 0-3.4-1-4.3-2.4" />
        <path d="M12.4 2.6v2.9h-2.9M3.6 13.4v-2.9h2.9" />
      </svg>
    );
  /*
    β›” THE FALLBACK IS NEUTRAL, and it was not the first time round. The default used to BE the
    pencil β€” a real member of the set (`update_record`) β€” so every kind with no arm silently
    borrowed "edit": `send_email`, `run_script` and `repeating_group` all drew it in the action
    menu, which reads as three actions that modify a record. A fallback that is a real member
    cannot be told apart from a match; this one can.
  */
  return (
    <svg {...common}>
      <rect x="3.2" y="3.2" width="9.6" height="9.6" rx="2.2" />
      <circle cx="8" cy="8" r="1.4" />
    </svg>
  );
}

/** The label a table key reads as. A raw `ut_9f3a…` on a card is a key, not a subtitle. */
function tableLabel(tables: UserTable[], key: string): string {
  if (!key) return "";
  return tables.find((t) => t.key === key)?.label || key;
}

export default function AutomationBuilder({
  automation,
  name,
  onNameText,
  onNameCommit,
  triggers,
  catalog,
  vocab,
  tables,
  oauth,
  busy,
  onPatch,
  onToggleNode,
  onPickTrigger,
  onRunNow,
  renderNodeBody,
  scheduleFace,
  showProperties,
  panelTabs,
  onStepPicked,
  schedules,
  walkTable,
  onTablesChanged,
  dirty,
}: Props) {
  const [sel, setSel] = useState<Sel>({ kind: "trigger", id: "" });
  const [picking, setPicking] = useState(false);
  const [adding, setAdding] = useState(false);
  /** The trigger key awaiting confirmation (image 6) β€” a change that can invalidate config. */
  const [confirmKey, setConfirmKey] = useState("");
  /** The card a reorder is hovering over (item 11). `""` = nothing is being dragged. */
  const [dragOver, setDragOver] = useState("");
  /**
   * β›” ONE DRAG SUPPRESSES EXACTLY ONE CLICK (item 11; `AutomationBoard`'s trap 1, which this
   * repo has already paid for once). Browsers can deliver a `click` after `dragend`, and the
   * thing under the pointer here is the card's own selector β€” so a finished reorder would ALSO
   * change which step the Properties panel is showing, which reads as the panel jumping on its
   * own. A ref and not state, because the click arrives before a re-render would land.
   */
  const draggedRef = useRef(false);
  /**
   * β›” THE TRIGGER MENU IS ANCHORED TO ITS BOX, AND THAT IS A LAYOUT FACT BEFORE IT IS A
   * DISMISSAL ONE (owner's ERROR 4, 2026-08-06). `<TriggerPicker variant="menu">` was rendered at
   * the BOTTOM of this component's fragment β€” a sibling of `.autox-flow` and the `.autox-props`
   * aside, inside `.auto-work`, which is `display: flex`. So opening it added a THIRD COLUMN to
   * the builder: the menu landed to the right of the Properties panel, off the edge of the
   * window, and the flow column (`flex: 1 1 auto; min-width: 0`) collapsed under it until
   * "Suggested triggers" wrapped one word per line and the canvas grew a horizontal scrollbar.
   * Nothing was broken about the menu β€” it was in the wrong parent.
   *
   * It lives inside `.autox-main` beside its own button now, and this ref is what makes the pair
   * ONE unit: an outside mousedown must not count the button that opens it as "outside", or the
   * click would close and reopen it forever. `TriggerPicker`'s own doc says the caller owns
   * open-ness for the `menu` variant precisely because the caller owns the anchor.
   */
  const addWrap = useRef<HTMLDivElement | null>(null);

  // Escape and an outside click both close it β€” the `field` variant's rule, applied to the twin
  // that had neither. Without this the empty state's menu was a one-way door: every row picks a
  // trigger, so changing your mind meant picking one you did not want.
  useEffect(() => {
    if (!picking) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setPicking(false);
    };
    const onDown = (e: MouseEvent) => {
      if (!addWrap.current?.contains(e.target as Node)) setPicking(false);
    };
    window.addEventListener("keydown", onKey);
    window.addEventListener("mousedown", onDown);
    return () => {
      window.removeEventListener("keydown", onKey);
      window.removeEventListener("mousedown", onDown);
    };
  }, [picking]);

  const trigger = automation.trigger || null;
  const triggerKey = trigger?.key || (automation.schedule?.enabled ? "schedule" : "manual");
  const options = triggers || [];
  const picked = options.find((t) => t.key === triggerKey) || null;
  const actions = automation.flow?.actions || [];
  const nodes = (automation.graph?.nodes || []).filter((n) => n.kind !== "trigger");
  const ops = vocab?.condOps || [];
  const nullaryOps = vocab?.nullaryCondOps || [];
  const table = tables.find((t) => t.key === (trigger?.table || "")) || null;

  /**
   * β›” HAS ANYTHING BEEN CHOSEN? β€” and the first version of this line was wrong in a way only
   * a screenshot showed.
   *
   * It read `!!trigger || key === "schedule" || key === "manual"`, and `triggerKey` DERIVES
   * "manual" whenever nothing is stored β€” so it was true for every automation ever, and the
   * Airtable empty state (image 1) was unreachable code that every gate was happy with.
   *
   * The honest test is what the DEFINITION holds, not what the picker displays: the engine
   * deliberately stores no trigger for manual/schedule ("`schedule` already owns the cron"), so
   * `trigger === null && !schedule.enabled` IS "nobody has decided yet". Manual is what that
   * state DOES, not a thing you pick out of it β€” which is why the suggested list below omits
   * it: an option whose selection stores nothing would bounce straight back to this state on
   * the next reload, and a control that undoes itself is worse than no control.
   */
  const chosen = !!trigger || !!automation.schedule?.enabled;
  /**
   * ⭐⭐ 2026-08-07 (owner report, the SECOND time on this feature) β€” *"I still can't do
   * Enrichment, when the Trigger is Manual, it says that I need to bound it to a database, how?"*
   *
   * β›” THE DATABASE PICKER EXISTED AND WAS UNREACHABLE FOR THE ONE TRIGGER THAT NEEDS IT MOST,
   * and the two decisions that combined to hide it were each locally right:
   *   1. `clean_trigger` STORES NOTHING for `manual` and `schedule` (`:8389`) β€” "storing a no-op
   *      trigger would be a second copy of that fact". So a manual automation holds `trigger:
   *      null` forever, by design.
   *   2. `chosen` is therefore FALSE for it (the note above says so explicitly), and W25/R14 hides
   *      the whole Configuration section until a trigger is `chosen`.
   * β‡’ The picker `caee549` added for exactly this case sits INSIDE that section, so picking
   * Manual could never reveal it. `run_plain` then refused with *"pick one on the trigger, or in
   * Properties"* β€” a sentence naming two doors while rendering neither. MEASURED in the live
   * nurilab store: `auto_2` "Enrichment test", `kind:'plain'`, `trigger:None`,
   * `config.targetTable:''`, one `enrich_instagram` action, unrunnable.
   *
   * ⚠ AND THE SCREEN DISAGREED WITH THE STORE, which is why the owner reasonably believed they
   * had picked something: `triggerKey` DERIVES `"manual"` when nothing is stored, so the panel
   * displays "Manual" over a definition that holds no trigger at all.
   *
   * β›” THE FIX IS NOT TO START STORING A MANUAL TRIGGER. The note above already argued that out
   * and it is still right β€” a control whose selection stores nothing bounces back on reload. What
   * was wrong is treating "no trigger stored" as "nothing to configure": a `plain` automation
   * whose trigger carries no table of its own ALWAYS has one thing to configure, the database its
   * steps walk, and that is true in exactly the state where `chosen` is false. So Configuration
   * opens for that too β€” the trigger-specific blocks inside are each keyed off `triggerKey` and
   * stay hidden on their own. That widening lives in the Properties panel beside the picker it
   * reveals (`needsOwnTable`), not here: `chosen` still means exactly what it says.
   */
  const configured = !trigger || trigger.configured !== false;

  /** Write one key of the trigger, keeping the rest β€” the engine merges against `previous`. */
  const patchTrigger = (patch: Record<string, unknown>) =>
    onPatch({ trigger: { key: triggerKey, ...patch } });

  /**
   * ⭐⭐ 2026-08-07 (owner report) β€” PATCH THE AUTOMATION'S OWN CONFIG.
   *
   * β›” IT SPREADS THE EXISTING CONFIG, and that is not defensive tidiness: `clean_definition`
   * takes `raw["config"]` WHOLE when it is a dict (`cfg_raw = raw.get("config") if isinstance(...)
   * else prev.get("config")`) β€” it does not merge. Sending `{targetTable: x}` alone would erase
   * the discovery predicates, the lanes and the schedule face in one keystroke.
   */
  const patchConfig = (patch: Record<string, unknown>) =>
    onPatch({ config: { ...((automation.config as Record<string, unknown>) || {}), ...patch } });

  const patchFlow = (next: Action[]) => onPatch({ flow: { actions: next } });

  /**
   * ⭐ ONE TREE WALKER (wave 24, C-FORK). Rewrite or drop any action anywhere, branches included:
   * `f` returns a replacement, or `null` to remove it.
   *
   * β›” THIS REPLACED FOUR HAND-ROLLED WALKS, and they were four places to forget the same thing.
   * A group's children moved from `config.actions` to `config.branches[].actions` this wave, so
   * every one of them would have quietly stopped descending into a fork β€” editing, deleting or
   * counting nothing inside it, with `tsc` perfectly happy because `config` is
   * `Record<string, unknown>` and an absent key is just `undefined`. The failure would have been
   * "the card is there and the delete button does nothing", per action, per fork.
   */
  const mapTree = (list: Action[], f: (a: Action) => Action | null): Action[] =>
    (list || [])
      .map((a) => {
        const next = f(a);
        if (next === null) return null;
        if (next.kind !== "group") return next;
        const brs = groupBranches(next);
        if (!brs.length) return next;
        return {
          ...next,
          config: {
            ...next.config,
            branches: brs.map((br) => ({ ...br, actions: mapTree(br.actions || [], f) })),
          },
        };
      })
      .filter((a): a is Action => a !== null);

  /** Replace one action anywhere in the tree, forks included β€” ids are stable server-side. */
  const editAction = (id: string, change: (a: Action) => Action) =>
    patchFlow(mapTree(actions, (a) => (a.id === id ? change(a) : a)));

  const dropAction = (id: string) => {
    // ⚠ REMOVING THE LAST ACTION IN A BRANCH IS REFUSED BY THE SERVER ("a branch with no actions
    // inside it does nothing") and the refusal is printed verbatim, as every other one is. Not
    // pre-empted here: a client that predicted it would be a second validator, and the honest
    // repair β€” delete the branch, not its last child β€” is one the reader can act on.
    patchFlow(mapTree(actions, (a) => (a.id === id ? null : a)));
    if (sel.kind === "action" && sel.id === id) setSel({ kind: "trigger", id: "" });
  };

  /**
   * REORDER (owner item 11). The whole `flow.actions` list goes back through `patchFlow` β€” the
   * same door every other edit uses β€” rather than a bespoke move endpoint, because the engine
   * already validates a whole flow and a second write path would be a second thing to keep
   * agreeing with `clean_actions`.
   *
   * ⚠ TOP-LEVEL SIBLINGS ONLY, deliberately, and it is a SCOPE rather than an oversight: a card
   * inside a conditional group is not `draggable` at all, so there is no affordance that quietly
   * does nothing. Group children are about to stop living under `config.actions` and start living
   * under `config.branches[].actions` (C-FORK), and building a tree-walking reorder against a
   * shape this same wave replaces would be work done twice with a window of wrongness in between.
   */
  const moveAction = (dragId: string, dropId: string) => {
    const next = reorderList(actions, dragId, dropId);
    // `null` = same card, or one of them is not a top-level sibling. Nothing moved, so nothing
    // is written β€” an aborted drag must not PATCH the flow back over itself.
    if (next) patchFlow(next);
  };

  /**
   * β›” A NEW ACTION'S CONFIG MUST BE ONE THE SERVER ACCEPTS β€” and the first version of this
   * function got it wrong for FOUR of the five kinds, which is worth writing down because every
   * gate was green and the harness could not see it (SSR renders no click).
   *
   * MEASURED against `clean_actions` itself (`python -c` over the engine module, no server):
   *   `{values:{"":""}}`      -> "a value is written to a field with no name"
   *   `{table:"",values:…}`   -> the same, twice
   *   `{table:""}` (find)     -> "the find records action names no database"
   *   `{cond:…,actions:[]}`   -> "a conditional group with no actions inside it does nothing"
   * So clicking "Add β†’ Update record" would have produced a red banner and NO CARD. This is the
   * wave-22 discovery-predicate scar reproduced exactly ([[cg-condition-builder-items]] β€” every
   * default must be one the server takes), in a file whose own comment cites it.
   *
   * The seeds below are built from data this component already holds, and `seedFor` returns
   * NULL when it cannot build a legal one. A kind with no legal seed is offered DISABLED with
   * the reason, rather than offered and refused: the two states look identical to a user and
   * only one of them is honest.
   */
  /**
   * ⭐ THE WALKING RECORD'S COLUMNS (item 12a). Read off `walkTable`, NOT off `table`.
   *
   * `table` is the TRIGGER's database and it answers a different question β€” which columns the
   * trigger may watch or test. This one answers what the ACTIONS write to and what a branch's
   * condition compares, and on any automation without an event trigger (manual, schedule,
   * `ig_profile_match`) the two are not the same table at all: the first is empty and the second
   * is where all the records are. Reading actions' fields off the trigger is why every condition
   * inside a fork offered an empty picker.
   */
  const walkFields = (tables.find((t) => t.key === walkTable) || null)?.fields || [];
  const firstField = walkFields[0]?.key || "";
  const firstTable = tables[0] || null;
  const firstTableField = firstTable?.fields?.[0]?.key || "";

  const seedFor = (kind: string): Record<string, unknown> | null => {
    if (kind === "update_record")
      return firstField ? { values: { [firstField]: "" } } : null;
    if (kind === "create_record")
      return firstTable && firstTableField
        ? { table: firstTable.key, values: { [firstTableField]: "" } }
        : null;
    if (kind === "find_records")
      return firstTable ? { table: firstTable.key, cond: null, limit: 25 } : null;
    /*
      ⭐⭐ WAVE 31 Β· T38 (contract C5, owner ruling R10) β€” THE WEB READ, and this branch is here
      because a gate demanded it rather than because anybody remembered.

      β›” FLIPPING `ready:True` ON THE SERVER IS NOT MOUNTING AN ACTION. `verify_automation_ui`'s
      seed check DERIVES its subject from the server catalog, so the moment `web_read` became
      ready it went red with `MISSING: ['web_read']` β€” the action would have rendered faded,
      labelled "Needs a database" (a claim about databases, which is not the problem) and been
      permanently unclickable. That is D-79's scar exactly, and the check written after it is what
      caught the repeat. A capability is reachable when the SERVER offers it, the ENGINE dispatches
      it and the CLIENT can seed it; two out of three ships an invisible feature.

      ⚠ THE SEED IS DELIBERATELY BLANK, and the server was changed to accept that. `url`,
      `selector` and `field` are what a person types in the panel, so requiring them at validation
      time would make a freshly-added step refuse itself β€” the wave-23 illegal-default-seed defect.
      `_clean_action_config` stores an unconfigured step and the RUNNER fails closed with a
      sentence naming what is missing, which is the same posture the enrich arm takes with
      `profileField`. The values below mirror that validator's defaults exactly.
    */
    if (kind === "web_read")
      return { ...WEB_SEEDS.web_read, field: firstField || "" };
    /*
      ⭐⭐ W31 QA β€” THE OTHER FOUR WEB KINDS, and the comment above predicted this exactly one
      kind early. When the owner's revocation of D-51/R5 flipped `web_goto`/`web_fill`/`web_click`/
      `web_repair` to `ready:True`, the catalog-derived seed check went red with
      `MISSING: ['web_click','web_fill','web_goto','web_repair']` β€” all four would have painted
      faded and PERMANENTLY UNCLICKABLE while the server, the seam and the runner all offered them.
      Three out of four is still an invisible feature.

      ⚠ BLANK FOR THE SAME REASON `web_read` IS BLANK: `url` / `selector` / `value` are what a
      person types in the panel, so seeding them with anything real would either lie or refuse
      itself at validation time. `_clean_action_config` stores the unconfigured step and the RUNNER
      fails closed naming what is missing (`WEB_REQUIRED`, per kind) β€” which is why these seeds
      carry no field the validator would reject and no field the runner would silently ignore.
      ⚠ `web_fill` seeds `secret: false` EXPLICITLY rather than omitting it: the flag decides
      whether the typed value is masked in the run log, and a masking control that only exists
      once somebody discovers it is a control most people never turn on.
    */
    // ⚠ W33-T52 β€” one branch over `WEB_SEEDS`, not four literals. The seed and the config panel
    // now read the same table, so a sixth web kind is ONE edit and cannot ship addable-but-
    // unconfigurable the way all five of these did.
    if (isWeb(kind)) return { ...WEB_SEEDS[kind] };
    // W33-T56 β€” the fuzzy step. Its own seed, because it is not a `web_*` kind (see AI_AGENT_SEED).
    if (kind === "ai_agent") return { ...AI_AGENT_SEED };
    /*
      ⭐⭐ 2026-08-07 (owner report) β€” THE ENRICH ACTION HAD NO BRANCH HERE, SO IT WAS
      PERMANENTLY UNCLICKABLE. `disabled={!c.ready || busy || !seedFor(c.kind)}` and this
      function's `return null` fallback meant the row rendered faded, labelled "Needs a
      database", with an EMPTY tooltip (`seedBlock` had no sentence for it either). The server
      declared it `ready:true`, its config panel was fully built and its runner was correct β€”
      one client-side list nobody updated made the whole capability unreachable. Owner:
      *"The enrichment action, says that it needs a database. So I can't even click it and
      assign a database? thats wicked."*

      β›” IT TAKES NO TABLE, AND THAT IS WHY THE OLD LABEL WAS ALSO WRONG. Enrichment acts on
      the record WALKING THE FLOW β€” the flow's own target database β€” so there is nothing to
      assign per action. `verify_automation`'s seed-coverage check now derives its subject from
      the server catalog, so the NEXT ready action added without a seed goes red instead of
      shipping invisible.

      The values mirror `clean_action_config`'s defaults exactly. A seed that disagreed with the
      validator is the wave-23 illegal-seed defect (four kinds shipped a red banner and no card).
    */
    /*
      ⭐⭐ WAVE 30 Β· W30-T23 / CONTRACT C3 β€” ONE ARM FOR BOTH ENRICH KINDS.
      The server's own validator branches on `ENRICH_KINDS = ("enrich_instagram","enrich_tiktok")`
      β€” ONE branch, one set of keys, with `postMetrics`/`commentMetrics` answered `False` for
      TikTok until W30-T10 wires post capture. So the seed is shared for the same reason: a seed
      that disagreed with the validator is the wave-23 illegal-seed defect (four kinds shipped a
      red banner and no card), and TWO seeds for one validator branch is that defect waiting.
      ⚠ The two metric keys are seeded `false` for BOTH, which is what the server already answers
      for TikTok β€” so nothing changes shape when T10 deletes its `and kind != "enrich_tiktok"`
      clause. Seeding them only for Instagram would have made T10 a client change as well.
      β›” THIS ARM AND ITS `seedBlock` SENTENCE HAD TO LAND TOGETHER. D-79's scar was exactly one
      of the two missing: the row rendered faded, labelled "Needs a database" β€” a claim about
      databases, which was not the problem β€” with an EMPTY tooltip.
    */
    if (isEnrich(kind))
      return {
        // ⭐ WAVE 28 Β· R5/R6 β€” `tier: "anonymous"` and `noFallback: false` are GONE from the seed.
        // R5 retired the free ladder from enrichment, so a new action must not be born naming a
        // source strategy the runner no longer consults. The server keeps ACCEPTING both keys on
        // stored definitions and ignores them (C2, D-65's law) β€” but a SEED is what a new step
        // starts with, and seeding a dead key is how a retired concept outlives its removal.
        // ⚠ `postMetrics`/`commentMetrics` stay `false` here and that is R6's ruling verbatim
        // ("always both off until toggled on"), matching `clean_action_config`'s reading of an
        // absent key so the seed and the validator cannot disagree.
        postMetrics: false, commentMetrics: false,
        dryRun: false, maxPosts: 10,
        fromView: "", sortField: "first_found", sortDir: "desc",
        // ⚠ `skipRecent: true` MATCHES `_ensure_enrich_step`'s server seed, deliberately. One
        // control must not have two defaults depending on whether the step was added by hand or
        // seeded onto an Instagram search β€” that is the split-default class this repo has paid
        // for twice ([[default-must-pass-its-own-guard]]). It also cannot surprise on first use:
        // nothing has an `Enriched at` yet, so the cooldown changes nothing until run two, which
        // is exactly when not re-paying is what you want.
        // β›” NOT the validator's default. `clean_action_config` reads an ABSENT key as False, so
        // every enrich action stored before today keeps the behaviour it already had β€” a seed is
        // what a new step starts with, never a rule applied retroactively (D-65).
        limit: 25, skipRecent: true, skipRecentDays: 30,
      };
    if (kind === "group")
      /*
        ⭐ RE-SEEDED FOR C-FORK, and the old seed would now be REFUSED. It was
        `{cond: null, actions: [child]}` β€” the pre-wave-24 shape, which `clean_actions` no longer
        accepts as a config: the fork's legs live under `branches` and `cond`/`actions` are gone
        from the group's own config entirely. Clicking "If / then" would have produced a red
        banner and no card, which is precisely the illegal-default-seed defect this function's
        header was written about, reproduced by the wave that quotes it.

        MEASURED against `clean_actions` rather than reasoned:
          Β· a branch with no actions      -> "a branch with no actions inside it does nothing"
          Β· so the one branch is born with the cheapest legal child, exactly as before β€” not a
            review, which would also mint a board stage nobody asked for by clicking "If / then".
        β›” `label: ""` ON PURPOSE. The SERVER letters the branches by index and calls a null-cond
        last leg "Otherwise", but it PRESERVES any label the client sends β€” so sending one would
        freeze it, and a branch labelled "A" would still say "A" after the branch above it was
        deleted. Sending nothing keeps the lettering correct by construction, and this fresh
        single branch reads "Otherwise" until it is given a condition, which is what it is.
      */
      return firstField
        ? {
            branches: [
              {
                id: "b1",
                label: "",
                cond: null,
                actions: [
                  { id: "", kind: "update_record", enabled: true, when: null,
                    config: { values: { [firstField]: "" } } },
                ],
              },
            ],
          }
        : null;
    return null;
  };

  /** Why a kind cannot be added yet β€” the server's own precondition, said before the click. */
  const seedBlock = (kind: string): string => {
    if (kind === "update_record" || kind === "group")
      return "Name the trigger's database first. This needs a column to write.";
    if (kind === "create_record" || kind === "find_records")
      return "There is no blank database to point at yet.";
    /*
      β›” NOT `""`. An empty string here renders "Needs a database" with NO tooltip β€” a disabled
      control that will not say why, which is exactly how the enrich action sat unreachable and
      unexplained. A kind that reaches this line is one somebody forgot to seed, so the fallback
      says the true thing rather than the plausible one: the label above claims a database is
      missing, and for a forgotten seed that claim is a guess.
    */
    return "This action cannot be added yet. It has no starting configuration.";
  };

  /**
   * ⚠ `into` NAMES A BRANCH NOW, not just a group (C-FORK). A fork has several legs and "add an
   * action to this group" stopped being a complete instruction the moment it did β€” putting it in
   * the first branch by default would silently attach work to whichever leg happens to be first.
   */
  const addAction = (kind: string, into?: { actionId: string; branchId: string }) => {
    const seed = seedFor(kind);
    if (!seed) return;
    const fresh: Action = { id: "", kind, enabled: true, when: null, config: seed };
    if (!into) {
      patchFlow([...actions, fresh]);
    } else {
      patchFlow(
        mapTree(actions, (a) => {
          if (a.id !== into.actionId) return a;
          return {
            ...a,
            config: {
              ...a.config,
              branches: groupBranches(a).map((br) =>
                br.id === into.branchId
                  ? { ...br, actions: [...(br.actions || []), fresh] }
                  : br
              ),
            },
          };
        })
      );
    }
    setAdding(false);
  };

  /** Add an empty-conditioned leg to a fork. The server letters it and enforces the ceiling. */
  const addBranch = (actionId: string) => {
    const seedChild = seedFor("update_record");
    if (!seedChild) return;
    patchFlow(
      mapTree(actions, (a) => {
        if (a.id !== actionId) return a;
        const brs = groupBranches(a);
        return {
          ...a,
          config: {
            ...a.config,
            // ⚠ APPENDED LAST, and the server refuses a null-cond branch that is not last β€” so a
            // fork that already ends in an Otherwise leg refuses this with its own sentence
            // rather than silently burying the catch-all in the middle, where every branch below
            // it would be dead code.
            branches: [
              ...brs,
              { id: "", label: "", cond: null,
                actions: [{ id: "", kind: "update_record", enabled: true, when: null,
                  config: seedChild }] },
            ],
          },
        };
      })
    );
  };

  const dropBranch = (actionId: string, branchId: string) =>
    patchFlow(
      mapTree(actions, (a) => {
        if (a.id !== actionId) return a;
        const kept = groupBranches(a).filter((br) => br.id !== branchId);
        // A fork with no legs at all "does nothing" β€” the server says so; do not send an empty
        // list dressed up as an edit.
        if (!kept.length) return a;
        return { ...a, config: { ...a.config, branches: kept } };
      })
    );

  /**
   * R8's numbers for the whole flow, computed ONCE per render rather than per card β€” the map is
   * built by walking the tree, so asking it per card would be quadratic in a deep fork, and more
   * importantly a per-card computation could not see its siblings and would have to re-derive
   * the position it is being told.
   */
  const stepNos = numberActions(actions);

  /**
   * ⭐ THE ACTION MENU'S GROUP ORDER, FROM THE SERVER (owner item 12b, contract C-ACT).
   *
   * β›” NEVER A LITERAL LIST OF GROUP NAMES HERE. The server ships `groupOrder` on every catalog
   * row (1 Web action Β· 2 Database Β· 3 Connected Β· 4 Advanced logic, derived server-side from one
   * table so two rows cannot disagree about their own group). A client
   * `["Web action", "Database", …]` would be a second copy of the catalog's structure, and the
   * day the engine adds or renames a group the client drops it off the end β€” or drops it
   * entirely β€” without anything going red.
   *
   * ⚠ AN UNORDERED GROUP SORTS LAST, NOT FIRST, which the server's own gate asserts. `Infinity`
   * and not `0`: a missing number meant "before everything" under a naive `|| 0`, so a server
   * older than this client would have led its menu with whatever it had failed to classify.
   * ⚠ The sort is STABLE over first appearance, so two groups sharing an order keep the payload's
   * sequence rather than an arbitrary one.
   */
  /* ⭐ WAVE 27 Β· ITEM 33 / C4 β€” the ordering above moved into `steps.ts` as `groupActions`,
     which does the SAME arithmetic and additionally nests connector rows. Two reasons it moved
     rather than gaining a clause here: `groupTriggers` already does exactly this for the trigger
     picker and the two must not drift, and a pure function in `steps.ts` is one node can run β€”
     `verify_steps` exercises the nest, which no amount of JSX here could be tested against. */
  const menuGroups = groupActions(catalog);

  /** ONE action row, so the nested and un-nested lists cannot render differently. */
  const actionRow = (c: ActionCatalogRow) => (
    <button
      key={c.kind}
      type="button"
      className={"autox-menu-row" + (c.ready && seedFor(c.kind) ? "" : " is-planned")}
      disabled={!c.ready || busy || !seedFor(c.kind)}
      title={c.ready && !seedFor(c.kind) ? seedBlock(c.kind) : c.detail}
      onClick={() => addAction(c.kind)}
    >
      <span className={"autox-card-mark" + (hasBrandKind(c.kind) ? " is-brand" : "")}>
        <ActionMark kind={c.kind} />
      </span>
      <span className="autox-menu-text">
        <span className="autox-menu-label">
          {c.label}
          {!c.ready ? (
            <span className="autox-soon">Coming soon</span>
          ) : !seedFor(c.kind) ? (
            /* NOT the same state as "coming soon", so not the same word: this one is built and
               waiting on THIS automation, and the title says exactly what is missing. */
            <span className="autox-soon">Needs a database</span>
          ) : null}
        </span>
        <span className="autox-menu-detail">{c.detail}</span>
      </span>
    </button>
  );

  // ── the centre column ────────────────────────────────────────────────────────────────────
  const chip = () => {
    if (!chosen) return null;
    if (!configured)
      return (
        <span className="autox-chip is-warn" title="This trigger cannot fire until it is finished">
          Finish configuration
        </span>
      );
    if (trigger?.paused)
      return <span className="autox-chip is-warn">Paused</span>;
    if (picked && picked.ready === false)
      return <span className="autox-chip is-warn">Not set up</span>;
    const last = automation.runs?.[0];
    if (last)
      return (
        <span className="autox-chip is-ok" title={last.summary}>
          {last.ok ? "Last run succeeded" : "Last run failed"}
        </span>
      );
    return null;
  };

  const actionCard = (a: Action, depth: number, hasNext = false): ReactNode => {
    const row = catalog.find((c) => c.kind === a.kind);
    const isGroup = a.kind === "group";
    const branches = isGroup ? groupBranches(a) : [];
    /**
     * ⭐ THE PERMANENT FIRST STEP (owner ruling 2026-08-06). An Instagram search produces rows
     * and has nowhere to put them until something writes them, so Create record is step 1 and
     * stays. DERIVED from the same rule the server enforces (`ig_action_pinned`) rather than
     * from a stored flag β€” and the control is HIDDEN rather than disabled, because the server
     * re-inserts the action on the next save, so a delete button here would appear to work and
     * then silently undo itself.
     */
    const pinned =
      automation.kind === "discover_instagram" && depth === 0 && a.id === actions[0]?.id;
    /**
     * ⭐⭐ WAVE 32 Β· T45 (owner item 10) β€” CONFIGURED / UNCONFIGURED, and the SERVER decides.
     *
     * β›” NOT COMPUTED HERE. The same `engine.action_needs` that fills this list also refuses the
     * run (`400 action_unconfigured`, and `run_now` for the tick and the webhook), so a card
     * cannot claim Configured over an action the run will reject. A client-side "does it look
     * filled in" test would be a second rule that agrees until one of them learns a new key.
     * ⚠ Nested cards get it too: the list is keyed by ACTION ID over the whole flow, branches
     * included, and a step inside an If / then is the one a person is least able to see.
     */
    const needs = (automation.unconfigured || []).find((u) => u.id === a.id)?.needs || [];
    /** Only TOP-LEVEL cards reorder (see `moveAction`) β€” depth 0, and never while a write is up. */
    const canDrag = depth === 0 && !busy && !pinned;
    return (
      <div className="autox-actionwrap" key={a.id}>
        <div
          className={
            "autox-card" +
            (sel.kind === "action" && sel.id === a.id ? " is-selected" : "") +
            (a.enabled ? "" : " is-off") +
            (isGroup ? " is-group" : "") +
            /* ⚠ THE GUARD IS NOT DECORATION. `dragOver` idles at `""` and a fresh action carries
               `id: ""` until the server names it, so a bare `dragOver === a.id` would be
               `"" === ""` β€” TRUE AT REST β€” and every new card would paint as a drop target from
               its first frame. That is wave 20's `is-folddrag` defect exactly, which shipped and
               was seen by the owner before any gate noticed. */
            (dragOver && dragOver === a.id ? " is-dropinto" : "")
          }
          draggable={canDrag}
          onDragStart={
            canDrag
              ? (e) => {
                  draggedRef.current = true;
                  e.dataTransfer.effectAllowed = "move";
                  e.dataTransfer.setData(ACTION_DRAG_TYPE, a.id);
                }
              : undefined
          }
          onDragOver={
            canDrag
              ? (e) => {
                  // Somebody else's drag β€” a file, a nav row, selected text β€” is not ours to
                  // accept. Without this test the card would light up for anything dragged over
                  // it and then swallow the drop.
                  if (!e.dataTransfer.types.includes(ACTION_DRAG_TYPE)) return;
                  e.preventDefault();
                  e.dataTransfer.dropEffect = "move";
                  setDragOver(a.id);
                }
              : undefined
          }
          onDragLeave={
            canDrag
              ? (e) => {
                  // Moving onto a CHILD of this card is not leaving it; without this the
                  // highlight flickers off every time the pointer crosses the title.
                  if (e.currentTarget.contains(e.relatedTarget as Node)) return;
                  setDragOver((cur) => (cur === a.id ? "" : cur));
                }
              : undefined
          }
          onDrop={
            canDrag
              ? (e) => {
                  const dragId = e.dataTransfer.getData(ACTION_DRAG_TYPE);
                  setDragOver("");
                  if (!dragId) return;
                  e.preventDefault();
                  moveAction(dragId, a.id);
                }
              : undefined
          }
          onDragEnd={() => {
            setDragOver("");
            // Cleared a tick later: the post-drag click arrives BEFORE this would run.
            window.setTimeout(() => {
              draggedRef.current = false;
            }, 0);
          }}
        >
          <button
            type="button"
            className="autox-card-hit"
            aria-pressed={sel.kind === "action" && sel.id === a.id}
            onClick={() => {
              // The one click a finished drag is allowed to cost is this one.
              if (draggedRef.current) return;
              setSel({ kind: "action", id: a.id });
              // ⭐ WAVE 27 Β· C11 β€” clicking a step SHOWS its Properties. The panel is
              // one of two that share the column now, and a click that configured the
              // invisible one would read as a click that did nothing.
              onStepPicked();
            }}
          >
            {/* ⭐ R8's STEP NUMBER, computed once for the whole flow (`numberActions`). The
                TRIGGER carries no number at all β€” that is the ruling, and it reverses wave 21's
                "Step 1 is always the Trigger" β€” so the numbers here start at 1 on the first
                ACTION. A fork occupies one number and its branches consume none. */}
            <span className="autox-card-n">{stepNos.get(a.id) || ""}</span>
            <span className={"autox-card-mark" + (hasBrandKind(a.kind) ? " is-brand" : "")}>
              <ActionMark kind={a.kind} />
            </span>
            <span className="autox-card-text">
              <span className="autox-card-title">
                {/* β›” NOT "If conditions are met" ANY MORE, and the literal was the problem
                    rather than the wording. C-ACT relabels the `group` kind to "If / then" on
                    the SERVER, so a hard-coded title here was a client paraphrase of a server
                    vocabulary β€” it would have gone on saying the old words after the catalog
                    changed, which is the one failure this file's header names twice. */}
                {row?.label || a.kind}
              </span>
              {isGroup ? (
                <span className="autox-card-sub">
                  {branches.length === 1
                    ? "1 branch"
                    : `${branches.length} branches`}
                </span>
              ) : (
                <span className="autox-card-sub">{actionSub(a, tables)}</span>
              )}
              {/* β›” THE LABEL IS ON EVERY CARD, IN BOTH STATES. Item 10 asks for
                  "Configured / Unconfigured" β€” showing only the bad one would make a configured
                  action indistinguishable from an action this build has no opinion about, which
                  is the question the label exists to answer. The Unconfigured one carries WHAT is
                  missing, because "Unconfigured" alone on a five-field step is a hunt. */}
              <span
                className={"autox-card-state" + (needs.length ? " is-off" : " is-on")}
                title={needs.length ? `Still needs ${needs.join(", ")}` : undefined}
              >
                {needs.length ? `Unconfigured. Needs ${needs.join(", ")}` : "Configured"}
              </span>
            </span>
          </button>
          {pinned ? (
            <span className="autox-card-pin" title="Every search saves what it finds">
              Always first
            </span>
          ) : (
            <button
              type="button"
              className="autox-card-drop"
              disabled={busy}
              aria-label={`Remove ${row?.label || a.kind}`}
              title={`Remove ${row?.label || a.kind}`}
              onClick={() => dropAction(a.id)}
            >
              <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                  strokeLinecap="round" />
              </svg>
            </button>
          )}
        </div>

        {/*
          ⭐ THE FORK (owner item 12a, ruling R8, contract C-FORK). A group used to hold ONE
          nested column; it now holds a LETTERED LANE PER BRANCH, because R8 rules that a fork
          occupies one step number and its legs are alternatives rather than later steps.

          THE LETTER AND THE "Otherwise" ARE THE SERVER'S WORDS β€” `br.label`, printed, never
          composed. `clean_actions` letters by index and names a null-cond last leg "Otherwise",
          so the lanes re-letter themselves correctly when one is deleted.
          The nesting ceiling is still the SERVER's `maxGroupDepth`, so the add-here affordance
          disappears at exactly the depth `clean_actions` refuses.
        */}
        {isGroup ? (
          <div className="autox-branches">
            {branches.map((br) => (
              <div className="autox-branch" key={br.id || br.label}>
                <div className="autox-branch-head">
                  <span className="autox-branch-letter">{br.label}</span>
                  <span className="autox-branch-cond">
                    {/* ⚠ NOT A RENDERED CONDITION β€” the tree is edited in Properties, and a
                        second editable copy here would be two controls for one fact. This says
                        only WHICH leg you are looking at. A null cond is the catch-all, and the
                        server has already labelled it, so this says nothing twice. */}
                    {br.cond ? "when its conditions match" : "everything else"}
                  </span>
                  {branches.length > 1 ? (
                    <button
                      type="button"
                      className="autox-branch-x"
                      disabled={busy}
                      aria-label={`Remove branch ${br.label}`}
                      title={`Remove branch ${br.label}`}
                      onClick={() => dropBranch(a.id, br.id)}
                    >
                      <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                        <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                          strokeLinecap="round" />
                      </svg>
                    </button>
                  ) : null}
                </div>
                <div className="autox-nest">
                  {(br.actions || []).map((k) => actionCard(k, depth + 1))}
                  {depth + 1 < (vocab?.maxGroupDepth ?? 2) || !(br.actions || []).length ? (
                    <button
                      type="button"
                      className="autox-add is-nested"
                      disabled={busy || !seedFor("update_record")}
                      title={seedFor("update_record") ? undefined : seedBlock("update_record")}
                      onClick={() => addAction("update_record", { actionId: a.id, branchId: br.id })}
                    >
                      + Add an action in {br.label}
                    </button>
                  ) : null}
                </div>
              </div>
            ))}
            <button
              type="button"
              className="autox-add is-nested"
              disabled={busy || !seedFor("update_record")}
              title={seedFor("update_record") ? undefined : seedBlock("update_record")}
              onClick={() => addBranch(a.id)}
            >
              + Add a branch
            </button>
          </div>
        ) : null}

        {/*
          THE ARROW BACK INTO THE FLOW (item 12a). The lanes are alternatives and exactly one of
          them runs β€” the engine takes the first matching branch and breaks β€” so they REJOIN, and
          without a mark saying so a fork at the end of a column reads as several parallel endings.
          Drawn only when there IS a next step to rejoin: an arrow into nothing is a promise the
          flow does not keep.
        */}
        {isGroup && hasNext ? (
          <div className="autox-merge" aria-hidden="true">
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor"
              strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
              <path d="M8 2.6v10.8M5.2 10.6 8 13.4l2.8-2.8" />
            </svg>
          </div>
        ) : null}
      </div>
    );
  };

  return (
    <>
      <div className="autox-flow">
        {/* ── TRIGGER ─────────────────────────────────────────────────────────────────── */}
        <div className="autox-step">
          <div className="autox-side">
            <span className="autox-tag">Trigger</span>
            {chip()}
          </div>
          <div className="autox-main">
            {chosen && options.length ? (
              <div
                className={
                  "autox-card is-trigger" + (sel.kind === "trigger" ? " is-selected" : "")
                }
              >
                <button
                  type="button"
                  className="autox-card-hit"
                  aria-pressed={sel.kind === "trigger"}
                  onClick={() => {
                    setSel({ kind: "trigger", id: "" });
                    onStepPicked();          // C11, same rule as an action card
                  }}
                >
                  <span
                    className={"autox-card-mark" + (hasBrandKind(triggerKey) ? " is-brand" : "")}
                  >
                    <TriggerMark kind={triggerKey} />
                  </span>
                  <span className="autox-card-text">
                    <span className="autox-card-title">
                      {picked?.label || triggerKey}
                    </span>
                    {trigger?.table ? (
                      <span className="autox-card-sub">
                        In {tableLabel(tables, trigger.table)}
                      </span>
                    ) : null}
                  </span>
                </button>
              </div>
            ) : (
              /*
                THE EMPTY STATE (image 1): a dashed add-box and the server's own suggested
                triggers. One line of chrome, no tour (R13) β€” the list IS the explanation, and
                it is the server's list so it cannot describe a trigger we removed.
              */
              <>
                {/* THE BOX AND ITS MENU ARE ONE UNIT (see `addWrap`). The menu USED to render at
                    the bottom of this component, outside `.autox-flow` entirely, and became a
                    third column of the flex row that holds the canvas and Properties β€” the
                    owner's ERROR 4. */}
                <div className="autox-trigadd" ref={addWrap}>
                  <button
                    type="button"
                    className="autox-add is-empty"
                    disabled={busy || !options.length}
                    aria-haspopup="listbox"
                    aria-expanded={picking}
                    onClick={() => setPicking((v) => !v)}
                  >
                    + Add trigger
                  </button>
                  {/* ⭐ WAVE 25 item 5b (C2) β€” `TriggerPicker`, the SAME component Properties β†’
                      Trigger details renders in its compact form. Category first (Time /
                      Database / Connector) with connector rows nested under their product. */}
                  {picking ? (
                    <TriggerPicker
                      variant="menu"
                      options={options}
                      value={triggerKey}
                      disabled={busy}
                      onPick={onPickTrigger}
                      onDismiss={() => setPicking(false)}
                    />
                  ) : null}
                </div>
                {options.length ? (
                  <div className="autox-suggest">
                    <p className="autox-suggest-head">Suggested triggers</p>
                    {options
                      // ⭐ 2026-08-07 (owner ruling) β€” MANUAL IS OFFERED AGAIN. It was excluded
                      // (`t.key !== "manual"`) because picking it stored NOTHING and bounced
                      // straight back to this empty state β€” "a control that undoes itself is
                      // worse than no control", correct while that was true. `clean_trigger` now
                      // STORES `{key:'manual'}`, so the pick sticks, `chosen` goes true and
                      // Configuration opens. Hiding it now would leave the one trigger a person
                      // most expects to find as the only one they cannot choose.
                      .filter((t) => t.ready !== false && !t.planned)
                      .slice(0, SUGGESTED)
                      .map((t) => (
                        <button
                          key={t.key}
                          type="button"
                          className="autox-suggest-row"
                          disabled={busy}
                          onClick={() => onPickTrigger(t.key)}
                        >
                          <span
                            className={
                              "autox-card-mark" + (hasBrandKind(t.key) ? " is-brand" : "")
                            }
                          >
                            <TriggerMark kind={t.key} />
                          </span>
                          {t.label}
                        </button>
                      ))}
                  </div>
                ) : (
                  <p className="auto-note">This server did not offer a trigger list.</p>
                )}
                {/* ONE LINE (R13), and it is what is TRUE of this state rather than a caption
                    for the box above it: with nothing chosen, Run now is the only thing that
                    starts this automation. Airtable's empty state means "it cannot run"; ours
                    does not, and saying so is the difference between a screen that is honest
                    and one that merely looks the same. */}
                <p className="auto-hint">Until then, only Run now starts it.</p>
              </>
            )}
          </div>
        </div>

        {/* ── ACTIONS ─────────────────────────────────────────────────────────────────── */}
        <div className="autox-step">
          <div className="autox-side">
            <span className="autox-tag">Actions</span>
          </div>
          <div className="autox-main">
            {actions.map((a, i) => actionCard(a, 0, i < actions.length - 1))}

            {/*
              β›” THE MACHINE STEPS ARE NOT CARDS ANY MORE (owner item 5, contract C-CFG). They
              were engine-derived read-only cards sitting under the owner's own actions β€” "fetch
              the page", "Bright Data", "Anonymous", "Write" β€” so the centre column mixed two
              different things: what the AUTOMATION is, which nobody chose and nobody can reorder,
              and what the OWNER added, which is the whole subject of this builder. Their
              configuration and their switches moved to Properties β†’ Configuration β†’
              "How this fetches", one section per panel.

              ⚠ THE ENGINE STILL RUNS THEM. `graph()` emits the same nodes; this surface simply
              stops DRAWING them, which is why the switches had to move rather than go β€” R7 names
              Bright Data (money) and Write's dry run (reads and reports without writing a row) as
              controls that must survive the cards that carried them.
            */}

            <button
              type="button"
              className="autox-add"
              disabled={busy || !catalog.length}
              onClick={() => setAdding((v) => !v)}
            >
              + Add advanced logic or action
            </button>

            {/* THE ACTION MENU (images 7/8): the server's catalog, grouped by its own `group`
                key, with `ready:false` rows faded and carrying the server's reason. A shorter
                menu would imply those actions do not exist β€” the owner asked to see all of
                them, and `clean_actions` refuses the unready ones at the door, so faded is a
                wall rather than a decoration. */}
            {adding ? (
              <div className="autox-menu" role="menu">
                {menuGroups.map((g) => (
                  <div className="autox-menu-group" key={g.key}>
                    <p className="autox-menu-head">{g.key}</p>
                    {/* ⭐ WAVE 27 Β· ITEM 33 / C4 β€” the group's OWN rows first, then one nest per
                        connector. `<details>` rather than a hand-built disclosure: it IS the
                        chevron-and-submenu the reference shows, it opens on Enter and Space
                        without a keydown handler, and it needs no open/closed state of its own
                        to get wrong. Closed by default β€” the reference shows collapsed rows,
                        and a connector nobody is using should cost one line, not six. */}
                    {[...g.rows, ...g.sub].map((entry) => ("rows" in entry ? (
                      <details className="autox-menu-nest" key={`sub:${entry.key}`}>
                        <summary className="autox-menu-row autox-menu-sum">
                          {/* ⭐ WAVE 30 Β· ITEM 7 / R4 β€” THE COLLAPSED ROW GETS AN IDENTITY.
                              This is the row the owner clicks before choosing Instagram or
                              TikTok, and until now it was the only row in the menu with
                              nothing on its left: the chevron, then a bare word. The mark is
                              resolved from the connector KEY, so a connector the server adds
                              tomorrow gets a slot for free and simply renders no logo. */}
                          {brandForConnector(entry.key) ? (
                            <span className="autox-card-mark is-brand">
                              {brandForConnector(entry.key)}
                            </span>
                          ) : null}
                          <span className="autox-menu-text">
                            <span className="autox-menu-label">{entry.label}</span>
                            <span className="autox-menu-detail">
                              {entry.rows.length} action{entry.rows.length === 1 ? "" : "s"}
                            </span>
                          </span>
                        </summary>
                        {entry.rows.map((c) => actionRow(c))}
                      </details>
                    ) : actionRow(entry)))}
                  </div>
                ))}
              </div>
            ) : null}
          </div>
        </div>
      </div>

      {/* ── PROPERTIES ──────────────────────────────────────────────────────────────────── */}
      <aside
        className={"auto-panel autox-props" + (showProperties ? " is-appearing" : "")}
        aria-label="Properties"
        /* ⭐ WAVE 27 Β· C11 β€” HIDDEN, not unmounted, and that is deliberate. This panel holds
           live editing state (the name field's text, a half-typed cron); unmounting it on every
           toggle would discard whatever was in flight. `hidden` also takes it out of the
           accessibility tree, so a screen reader is not offered two panels when one is drawn. */
        hidden={!showProperties}
      >
        <div className="auto-panel-head">
          {panelTabs}
          {/*
            THREE STATES, because this panel now holds two save disciplines. The discrete choices
            (a trigger, an action, a switch, a branch) persist as they are made; the machine
            steps' fields, which moved in here with item 5, commit with the header's Save. A
            two-state stamp had to be wrong about one of them, and "All changes saved" printed
            over an unsaved column map is the direction that loses work.
          */}
          <span
            className={"autox-saved" + (busy ? " is-busy" : dirty ? " is-dirty" : "")}
          >
            {busy ? "Saving…" : dirty ? "Unsaved changes. Press Save" : "All changes saved"}
          </span>
        </div>

        {/*
          ⭐ THE NAME (item 15b). It is ABOVE the selection-dependent body rather than inside the
          trigger's face, because it is a property of the AUTOMATION and not of whichever step
          happens to be selected β€” clicking an action card must not make the name disappear.
          It commits on blur; the caller writes it and prints any refusal.
        */}
        <div className="auto-field">
          <label htmlFor="autox-name">Name</label>
          <input
            id="autox-name"
            className="auto-input"
            value={name}
            disabled={busy}
            placeholder="Name this automation"
            onChange={(e) => onNameText(e.target.value)}
            onBlur={() => onNameCommit()}
          />
        </div>

        {sel.kind === "trigger" ? (
          <TriggerProps
            automation={automation}
            triggerKey={triggerKey}
            options={options}
            picked={picked}
            table={table}
            tables={tables}
            ops={ops}
            nullaryOps={nullaryOps}
            vocab={vocab}
            oauth={oauth}
            busy={busy}
            nodes={nodes}
            onToggleNode={onToggleNode}
            renderNodeBody={renderNodeBody}
            onAskChange={setConfirmKey}
            onPatchTrigger={patchTrigger}
            onPatchConfig={patchConfig}
            onPickTrigger={onPickTrigger}
            onRunNow={onRunNow}
            scheduleFace={scheduleFace}
            schedules={schedules}
            /* ⭐ R14 β€” THE SAME `chosen` THE FLOW COLUMN USES, passed rather than recomputed.
               Both halves of one screen answer "has a trigger been picked": the centre column
               draws the empty state, Properties hides Configuration. Two derivations of that
               would eventually disagree, and the screen would then show an empty-state add-box
               beside a filled-in Configuration section β€” which is not a state the product has. */
            chosen={chosen}
          />
        ) : (
          <ActionProps
            action={findAction(actions, sel.id)}
            /* ⭐ THE SAME RULE `actionCard` DERIVES AND THE SERVER ENFORCES (`ig_action_pinned`),
               passed down rather than re-derived a third time. The panel needs it because the
               pinned step is the one action in the product whose value map the ENGINE NEVER
               READS β€” see `ActionProps`. */
            pinned={
              automation.kind === "discover_instagram" && sel.id === actions[0]?.id
            }
            catalog={catalog}
            tables={tables}
            onTablesChanged={onTablesChanged}
            walkFields={walkFields}
            /* ⭐ WAVE 26 Β· ITEM 5 / R10 β€” REQUIRED, and it is NOT the same question as
               `walkFields`. An empty field list has two causes that need opposite answers: this
               flow has no record walking it at all (say so, point at the trigger), or it has one
               whose database has no columns yet (an empty picker is then correct). Passing only
               the list forced the panel to guess, which is how the empty picker that produced
               "the condition names no field" got shipped in the first place. */
            walkTable={walkTable}
            ops={ops}
            nullaryOps={nullaryOps}
            vocab={vocab}
            busy={busy}
            onEdit={(change) => editAction(sel.id, change)}
          />
        )}
      </aside>

      {/* THE CONFIRM (image 6). A trigger change can invalidate the configuration under it, so
          it ASKS β€” and it says what it will cost rather than "are you sure". */}
      {confirmKey ? (
        <div className="autox-confirm" role="dialog" aria-label="Change the trigger">
          <p className="autox-confirm-title">Change the trigger?</p>
          <p className="autox-confirm-body">
            Anything configured for {picked?.label || triggerKey} is dropped.
          </p>
          <div className="autox-confirm-acts">
            <button type="button" className="auto-btn" onClick={() => setConfirmKey("")}>
              Cancel
            </button>
            <button
              type="button"
              className="auto-btn is-danger"
              onClick={() => {
                onPickTrigger(confirmKey);
                setConfirmKey("");
              }}
            >
              Change trigger
            </button>
          </div>
        </div>
      ) : null}

      {/* β›” THE PICKER USED TO RENDER HERE, and here is outside both columns. `.auto-work` is a
          flex row of `.autox-flow` + `.autox-props`, so a third child was laid out as a third
          COLUMN β€” the menu appeared past the right edge of the Properties panel and squeezed the
          canvas until the suggested triggers wrapped one word per line (owner's ERROR 4). It is
          rendered beside its own "+ Add trigger" box now; see `addWrap`. */}
    </>
  );
}

/** One action's subtitle β€” what it will DO, composed from its own config. */
function actionSub(a: Action, tables: UserTable[]): string {
  const cfg = a.config || {};
  if (a.kind === "update_record") {
    const keys = Object.keys((cfg as { values?: Record<string, unknown> }).values || {})
      .filter(Boolean);
    return keys.length ? `Sets ${keys.join(", ")}` : "No values yet";
  }
  if (a.kind === "create_record") {
    const t = String((cfg as { table?: string }).table || "");
    return t ? `Into ${tableLabel(tables, t)}` : "No database yet";
  }
  if (a.kind === "find_records") {
    const t = String((cfg as { table?: string }).table || "");
    return t ? `In ${tableLabel(tables, t)}` : "No database yet";
  }
  return "";
}

function findAction(list: Action[], id: string): Action | null {
  for (const a of list) {
    if (a.id === id) return a;
    // ⚠ THROUGH THE BRANCHES (C-FORK). This read `config.actions`, which a fork no longer has β€”
    // so selecting any action inside one would have found nothing and the Properties panel would
    // have said "that action is no longer part of this flow" about a card visibly on screen.
    if (a.kind === "group")
      for (const br of groupBranches(a)) {
        const hit = findAction(br.actions || [], id);
        if (hit) return hit;
      }
  }
  return null;
}

/*
 * β›” `nodePanel()` IS GONE (item 5). It rendered ONE machine node's panel, chosen by the card the
 * reader had clicked, and included a "that step is no longer part of this automation" branch for
 * a selection the graph had since dropped. Both facts died with the cards: the panels are now
 * rendered together under "How this fetches", keyed by PANEL rather than by node id, so there is
 * no selection left to go stale.
 */

// ── the Properties panel's two faces ─────────────────────────────────────────────────────────

function TriggerProps({
  automation,
  triggerKey,
  options,
  picked,
  table,
  tables,
  ops,
  nullaryOps,
  vocab,
  oauth,
  busy,
  nodes,
  onToggleNode,
  renderNodeBody,
  onAskChange,
  onPatchTrigger,
  onPatchConfig,
  onPickTrigger,
  onRunNow,
  scheduleFace,
  schedules,
  chosen,
}: {
  automation: Automation;
  triggerKey: string;
  options: TriggerOption[];
  picked: TriggerOption | null;
  table: UserTable | null;
  tables: UserTable[];
  ops: string[];
  nullaryOps: string[];
  vocab?: FlowVocab;
  oauth: OAuthStatus | null;
  busy: boolean;
  /** The engine's machine steps (item 5) β€” their switches and bodies live under Configuration. */
  nodes: GraphNode[];
  onToggleNode: (nodeId: string) => void;
  renderNodeBody: (panel: string) => ReactNode;
  /** Ask before a trigger change that can invalidate the config under it (image 6). */
  onAskChange: (key: string) => void;
  onPatchTrigger: (patch: Record<string, unknown>) => void;
  /** Writes the automation's OWN config β€” the database a table-less trigger has nowhere
   *  else to name (owner report 2026-08-07). Spreads on the way in; see `patchConfig`. */
  onPatchConfig: (patch: Record<string, unknown>) => void;
  onPickTrigger: (key: string) => void;
  onRunNow: () => void;
  scheduleFace: ReactNode;
  schedules: boolean;
  /**
   * ⭐ WAVE 25 item 5b (ruling R14) β€” HAS A TRIGGER BEEN PICKED AT ALL?
   *
   * REQUIRED and passed IN, never re-derived: it is the same `chosen` the centre column gates its
   * empty state on, and the honest test is what the DEFINITION holds rather than what the picker
   * displays (`triggerKey` derives "manual" whenever nothing is stored, so anything computed from
   * it is true for every automation ever β€” a mistake this file already made once and only a
   * screenshot caught).
   */
  chosen: boolean;
}) {
  const trigger = automation.trigger || null;
  const provider = picked?.connect?.provider || "";
  const connected = !!(provider && oauth?.[provider]?.connected);
  const startUrl = picked?.connect?.startUrl || "";
  const needsTable = !!trigger && "table" in trigger;
  /**
   * ⭐⭐ 2026-08-07 β€” DOES THIS AUTOMATION HAVE TO NAME ITS OWN DATABASE?
   *
   * True for a `plain` automation whose trigger carries no table β€” which INCLUDES the state where
   * no trigger is stored at all, and that inclusion is the whole fix. `clean_trigger` stores
   * nothing for `manual`/`schedule` by design, so those automations hold `trigger: null`, `chosen`
   * is false, and W25/R14's "Configuration does not render until a trigger is picked" hid the
   * Database picker below from the exact automations that cannot get a database any other way.
   * The owner hit it twice: *"when the Trigger is Manual, it says that I need to bound it to a
   * database, how?"* β€” and the honest answer was that there was no how.
   *
   * ⚠ It is the SAME condition the picker itself renders on, named once and used twice, so the
   * section cannot open without the control or the control appear without its section.
   */
  const needsOwnTable = automation.kind === "plain" && !needsTable;
  const last = automation.runs?.[0];
  /** ITEM 22 / D-70 / R12 β€” the shared Run guard (see `runBlock`). */
  const runState = runBlock(automation);

  return (
    <>
      <h3>Trigger details</h3>
      <div className="auto-field">
        {/*
          ⭐ WAVE 25 item 5b (C2) β€” THE NATIVE `<select>` IS GONE, AND THIS IS THE OWNER'S ITEM.
          `reference/ERROR 3.png`: eleven triggers listed flat, in `<optgroup>`s captioned
          "Standard" and "Sources", with NO ICONS β€” four inches from a "+ Add trigger" menu that
          draws every one of them with a mark. It is the same `TriggerPicker` in both places now,
          category first, connector rows nested under Gmail / Webhooks / Scraper / TikTok.

          ⚠ `<label>` WITHOUT `htmlFor`, DELIBERATELY. The control is a `<button>` opening a
          listbox, not a form field with an id to point at; an `htmlFor` naming an element that
          is not a labelable control is a relationship a screen reader is told about and cannot
          use. The button carries its own accessible name from its content and `aria-haspopup`.

          β›” THE CONFIRM RULE STAYS HERE, where the automation is. A trigger change can invalidate
          the configuration under it, so it ASKS when there IS something configured (image 6) β€”
          and that is a fact about this automation, not about a picker. `TriggerPicker` reports a
          choice; what a choice COSTS is the builder's to know.
        */}
        {/* ⚠ NO CLASS. `.auto-field > label` already styles every label in this panel
            (3xs / 600 / muted), and `.auto-field-label` adds a 12px top margin for the
            headings that are NOT inside an `.auto-field`. Using it here would put this one
            label 12px lower than the six beside it β€” DESIGN.md 2's "a panel matches its
            SIBLING's rendered values", which is a rule about pixels, not about tokens. */}
        <label>Trigger type</label>
        <TriggerPicker
          variant="field"
          options={options}
          value={triggerKey}
          disabled={busy}
          onPick={(next) => {
            if (next === triggerKey) return;
            if (trigger && trigger.configured !== false) onAskChange(next);
            else onPickTrigger(next);
          }}
        />
      </div>
      {/*
        ⭐ THE DESCRIPTION IS THE SERVER'S, AND IT RIDES NOW (wave 24, C-TYPES). This block used
        to be a comment explaining why there was NO paragraph here: Airtable prints two sentences
        under this select (image 3), ours would have been a client paraphrase of a server
        vocabulary, and the note said "when `detail` rides, it renders here and cannot disagree
        with the engine". `TriggerOption.detail` landed this wave, so the paragraph is the
        engine's own sentence, printed verbatim and never composed with anything.
      */}
      {picked?.detail ? <p className="auto-hint">{picked.detail}</p> : null}
      {picked && picked.ready === false && !picked.planned ? (
        <div className="autob-needs">
          <span className="autob-needs-text">
            {connected
              ? "Connected. This trigger is still being switched on for this deployment."
              : "This trigger is not set up yet."}
          </span>
          {!connected && startUrl ? (
            <a className="auto-btn is-primary autob-connect" href={startUrl}>
              Connect
            </a>
          ) : null}
        </div>
      ) : null}

      {/*
        ⭐ WAVE 25 item 5b (ruling R14) β€” CONFIGURATION DOES NOT RENDER UNTIL A TRIGGER IS PICKED.
        Owner, verbatim: *"let's not show Configuration at the first creation (this is
        overwhelming for first time users)"*. A brand-new automation opens on the trigger picker
        with nothing chosen, and every control below is a question ABOUT a trigger β€” a Database
        select, watched columns, a view, a Gmail query, a hook URL. Asking them before there is a
        trigger to ask them about is a form for a decision nobody has made.

        β›” ONCE PICKED IT RENDERS EXPANDED, and that is the other half of the ruling rather than an
        omission: at that point the section is REQUIRED (`configured:false` rides the wire and the
        card says "finish configuration"), so a collapsed heading would hide the thing the surface
        is simultaneously telling the reader to go and do.

        ⚠ THE WHOLE SECTION, HEADING INCLUDED. Rendering the `<h3>` over nothing is the state R13
        forbids β€” a heading over an empty region says "there should be something here", which is a
        different and false statement. This is `null`, not an empty fragment.
      */}
      {/* ⭐ 2026-08-07 β€” `|| needsOwnTable`: R14's rule was "do not render Configuration before a
          trigger is picked", and it is intact for every trigger that stores one. What it must not
          also mean is "a manual automation has nothing to configure" β€” it has exactly one thing,
          the database its steps walk, and no other surface can name it. See `needsOwnTable`. */}
      {!chosen && !needsOwnTable ? null : (
      <>
      <h3>Configuration</h3>
      {needsTable ? (
        <div className="auto-field">
          <label htmlFor="autox-ttable">
            <span className="autox-req">*</span> Database
          </label>
          <select
            id="autox-ttable"
            className="auto-input"
            value={trigger?.table || ""}
            disabled={busy}
            onChange={(e) => onPatchTrigger({ table: e.target.value })}
            data-role="trigger-table"
          >
            <option value="">Select a database…</option>
            {trigger?.table && !tables.some((t) => t.key === trigger.table) ? (
              <option value={trigger.table}>{trigger.table} (not visible to you)</option>
            ) : null}
            {tables.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label}
              </option>
            ))}
          </select>
        </div>
      ) : null}

      {/*
        ⭐⭐ 2026-08-07 (owner report) β€” THE DATABASE A TABLE-LESS TRIGGER HAS NOWHERE ELSE TO NAME.
        Owner: *"how come, enrich instagram when standalone 'manual' trigger, doesn't have a
        database that it should point to? dont make this mistake again."*

        MEASURED across the trigger vocabulary: `manual`, `schedule` and `email` carry NO `table`,
        so `needsTable` is false and the picker above never rendered β€” while `AutomationDetail`'s
        Properties picker is gated to `scrape_db` / `field_instagram`, BOTH RETIRED KINDS. So
        **nothing in the client wrote `config.targetTable` for a `plain` automation**, and
        `run_plain` answered *"no database is bound yet β€” pick one on the trigger, or in
        Properties"*: a refusal naming two doors, neither of which existed. Every scheduled or
        manual flow β€” the owner's *"on a schedule, enrich these sets of influencer names"* β€” was
        unbuildable.

        β›” `plain` ONLY, and that is what keeps it from being a second control for one fact. Every
        other kind names its database somewhere of its own: an Instagram search through the pinned
        Create record (W25/R2 made that action authoritative and `targetTable` follows it), and the
        two retired kinds through their own Properties panels. Widening this would put two pickers
        on one key and let them disagree, which is the exact defect R2 was written to end.
      */}
      {needsOwnTable ? (
        <div className="auto-field">
          <label htmlFor="autox-cfgtable">
            <span className="autox-req">*</span> Database
          </label>
          <select
            id="autox-cfgtable"
            className="auto-input"
            data-role="config-table"
            value={String(
              (automation.config as { targetTable?: string } | undefined)?.targetTable || ""
            )}
            disabled={busy}
            onChange={(e) => onPatchConfig({ targetTable: e.target.value })}
          >
            <option value="">Select a database…</option>
            {tables.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label} ({t.rowCount} {t.rowCount === 1 ? "row" : "rows"})
              </option>
            ))}
          </select>
          <p className="auto-hint">
            The records this automation&rsquo;s steps walk. A trigger like Manual or a schedule does
            not name one on its own.
          </p>
        </div>
      ) : null}

      {triggerKey === "event_field" ? (
        <>
          {/*
            β›” "WATCHED COLUMN" IS GONE (owner item 7, C-TRIG law 4). "When a record matches
            conditions" is a FILTER, and a watched column was a second, different question
            answered in the same box β€” the trigger fired on a column changing AND on the
            conditions holding, which is two triggers wearing one name.
            ⚠ THE SERVER WENT FIRST, and that ordering was the point: `clean_trigger` stopped
            reading `field` (C posted law 4 done) BEFORE this control came out. Deleting the
            control while the validator still read the key would have left a stored watched
            column that nothing displays and nothing can clear β€” and deleting the key while the
            control still showed it would have made every Save silently drop what the user
            picked. The CONDITION is what completes this trigger now: with none, it rides
            `configured:false` and says so.
          */}
          <p className="auto-field-label">
            <span className="autox-req">*</span> Conditions
          </p>
          <CondBuilder
            cond={trigger?.when || null}
            onChange={(next) => onPatchTrigger({ when: next })}
            fields={table?.fields || []}
            ops={ops}
            nullaryOps={nullaryOps}
            maxDepth={vocab?.maxCondDepth ?? 3}
            maxChildren={vocab?.maxCondChildren ?? 12}
            disabled={busy}
          />
        </>
      ) : null}

      {triggerKey === "record_updated" ? (
        <div className="auto-field">
          <label htmlFor="autox-twatch">Watched columns</label>
          <select
            id="autox-twatch"
            className="auto-input"
            multiple
            size={5}
            value={trigger?.fields || []}
            disabled={busy}
            onChange={(e) =>
              onPatchTrigger({
                fields: Array.from(e.target.selectedOptions).map((o) => o.value),
              })
            }
          >
            {(table?.fields || []).map((f) => (
              <option key={f.key} value={f.key}>
                {f.label}
              </option>
            ))}
          </select>
          <p className="auto-hint">Select none to fire on any column.</p>
        </div>
      ) : null}

      {triggerKey === "enters_view" ? (
        <div className="auto-field">
          <label htmlFor="autox-tview">
            <span className="autox-req">*</span> View
          </label>
          {/*
            ⭐ FOUR STATES, AND THREE OF THEM ARE SENTENCES (owner item 8, C-TYPES).
            `views` now rides `GET /automations/tables`, so this control is live β€” but "drop the
            note" would have collapsed it to two states and rebuilt the exact defect the contract
            forbids. Absent and empty are DIFFERENT FACTS:
              Β· no database chosen        -> choose one first
              Β· `views` ABSENT            -> the server offered nothing (a server older than this
                                             client). Saying "no views" here would be a claim
                                             nobody measured.
              Β· `views` present and []    -> this database genuinely has none. That IS measured,
                                             and it is the one that tells the reader to go and
                                             make a view rather than to go and find an admin.
              Β· non-empty                 -> the picker.
          */}
          {!table ? (
            <p className="auto-note">Choose a database first.</p>
          ) : !table.views ? (
            <p className="auto-note">This server did not offer a view list for that database.</p>
          ) : !table.views.length ? (
            <p className="auto-note">
              That database has no saved views yet β€” make one on its grid and it appears here.
            </p>
          ) : (
            <select
              id="autox-tview"
              className="auto-input"
              value={trigger?.viewId || ""}
              disabled={busy}
              onChange={(e) => onPatchTrigger({ viewId: e.target.value })}
            >
              <option value="">Select a view…</option>
              {/*
                ⚠ THE STORED VALUE IS ALWAYS AN OPTION, and this control did not have that guard.
                A <select> whose `value` matches no <option> renders the FIRST one β€” here
                "Select a view…", whose value is `""` β€” so an `enters_view` trigger pointed at a
                view that has since been deleted, or at one the server deliberately withholds
                (another user's personal view, a share that does not name this viewer), would have
                LOOKED unconfigured and the next patch would have written the blank over it. This
                repo has paid for that twice; the two "(not in this database)" options elsewhere
                in this file exist for the same reason.
              */}
              {trigger?.viewId && !table.views.some((v) => v.id === trigger.viewId) ? (
                <option value={trigger.viewId}>{trigger.viewId} (not offered here)</option>
              ) : null}
              {table.views.map((v) => (
                <option key={v.id} value={v.id}>
                  {v.label}
                </option>
              ))}
            </select>
          )}
        </div>
      ) : null}

      {triggerKey === "email" ? (
        <div className="auto-field">
          <label htmlFor="autox-tquery">Gmail search</label>
          <input
            id="autox-tquery"
            className="auto-input"
            defaultValue={trigger?.query || ""}
            disabled={busy}
            placeholder="from:orders@example.com"
            // FREE TEXT COMMITS ON BLUR β€” per-keystroke would PATCH a half-typed query.
            onBlur={(e) => onPatchTrigger({ query: e.target.value })}
          />
        </div>
      ) : null}

      {triggerKey === "webhook" && trigger?.token ? (
        <div className="auto-field">
          <label htmlFor="autox-thook">Hook URL</label>
          <input
            id="autox-thook"
            className="auto-input is-mono"
            readOnly
            value={`/api/v1/automations/hook/${trigger.token}`}
          />
          <p className="auto-hint">Minted once. It survives every other change to this trigger.</p>
        </div>
      ) : null}

      {/* THE SCHEDULE, rendered by the one component that owns the cron round-trip.
          ⚠ NOT `triggerKey === "schedule"` ANY MORE (item 7, C-TRIG). `ig_profile_match` watches
          nothing β€” it MAKES rows, on the cron β€” so its Configuration carries these controls
          "always", and the caller says which keys those are. */}
      {schedules ? scheduleFace : null}
      {triggerKey === "manual" ? (
        <p className="auto-hint">
          It runs when you press Run once now, and nothing else starts it.
        </p>
      ) : null}
      </>
      )}

      {/*
        ⭐ HOW THIS FETCHES (owner item 5, contract C-CFG) β€” the machine steps' switches and
        config bodies, below the trigger's own fields, under ONE sub-heading.

        β›” ONE SECTION PER PANEL, NOT PER NODE (`groupByPanel`, and its note is the reason). Four
        of `field_instagram`'s nodes share `panel: "capture"` and both of `discover_instagram`'s
        share `panel: "find"`, so a section per node would print one body four times and mount the
        discovery filter twice against a single `preds` array.

        β›” AND THE SWITCHES ARE THE POINT, not a leftover. R7: Bright Data buys exact counts with
        MONEY and Write's switch is the difference between a run that writes rows and one that
        reads and reports. They were on the cards this wave deleted, so deleting the cards without
        moving them would have retired two shipped controls silently. Each still posts to the
        node-toggle door β€” the server decides what a switch means, this only says which node.

        `plain` automations have no machine nodes at all, so the whole section is absent for them
        rather than an empty heading (R6 makes that the common case from now on).

        ⭐ WAVE 26 Β· ITEM 17 / R15 β€” THE PROSE IS GONE AND THE SWITCHES STAYED, which is the whole
        ruling. The owner quoted this section back verbatim β€” *"How this fetches / Find profiles /
        Bio contains skincare… / Collect results / Takes about 20 minutes / Up to 10 profiles Β·
        about $0.025"* β€” and asked for it gone. Every line of that quote is server-composed
        (`automation_engine.graph`), and it maps EXACTLY onto three renderers, which is why the
        deletion could be surgical rather than a section removal:
          Β· `n.subtitle`        -> "Bio contains skincare…" and "Takes about 20 minutes" (`:5030`, `:5036`)
          Β· `g.nodes[0].detail` -> "Up to 10 profiles Β· about $0.025" (`:5032`) β€” the ESTIMATE LINE
          Β· `n.title`/`<h3>`    -> "How this fetches", "Find profiles", "Collect results" β€” KEPT
        β›” THE HEADING WAS A SYMPTOM, NOT THE SUBJECT. Deleting the section would have retired the
        Bright Data MONEY switch and the write node's DRY RUN with it β€” the two controls that were
        moved here precisely so deleting the cards would not retire them silently. They are the
        `n.toggle` block below and they are untouched.
        ⚠ `AutomationFind`'s "What it costs" estimate is NOT this line and is NOT in scope: it is
        the ANSWER to a button a person pressed, and it is the only surface carrying D-23's
        SPEC-basis caveat. The read-only paragraph went; the control did not.
      */}
      {nodes.length ? (
        <>
          <h3>How this fetches</h3>
          {groupByPanel(nodes).map((g) => (
            <div className="autox-machine" key={g.panel}>
              {g.nodes.map((n) => (
                <div className="autox-machine-row" key={n.id}>
                  <span
                    className={"autox-card-mark" + (hasBrandKind(n.kind) ? " is-brand" : "")}
                  >
                    <ActionMark kind={n.kind} />
                  </span>
                  <span className="autox-machine-text">
                    <span className="autox-machine-title">{n.title}</span>
                  </span>
                  {/* ⭐ ITEM 18 / R14 β€” the per-node status dot stood here and is deleted. The
                      node already carries its own `ActionMark` above; a coloured dot beside it was
                      the second thing on one row claiming to say what this step is. */}
                  {n.toggle ? (
                    <button
                      type="button"
                      className={"auto-step-switch" + (n.enabled ? " is-on" : "")}
                      disabled={busy}
                      aria-pressed={n.enabled}
                      aria-label={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
                      title={`${n.enabled ? "Turn off" : "Turn on"} ${n.title}`}
                      onClick={() => onToggleNode(n.id)}
                    >
                      <span className="auto-step-switch-knob" />
                    </button>
                  ) : null}
                </div>
              ))}
              {/* ⭐ ITEM 17 / R15 β€” THE ESTIMATE LINE STOOD HERE. `g.nodes[0].detail` is where
                  "Up to 10 profiles Β· about $0.025" reached the screen (composed at
                  `automation_engine.py:5032`), and the owner named it. It was the engine's own
                  sentence rather than a client paraphrase, which is why it was defensible and
                  why it still had to go: an accurate paragraph nobody asked for is still the
                  architecture explaining itself (DESIGN.md Β§4).
                  ⚠ The COST question keeps a home β€” "What it costs" in the Find panel below,
                  behind a press, carrying its own SPEC caveat. This line stated a price nobody
                  had asked for beside a control that was not about price. */}
              {renderNodeBody(g.panel)}
            </div>
          ))}
        </>
      ) : null}

      <h3>Test step</h3>
      {/*
        β›” HONEST TO OUR SEMANTICS, not to Airtable's. Airtable's "Test step" replays one step
        against a chosen record. Ours has no step-replay: the engine runs a whole automation. So
        the control says what it actually does β€” RUN IT β€” and the results below are the last
        real run's, from the run log, rather than a rehearsal nobody performed.
      */}
      {/* ⭐ ITEM 22 / D-70 / R12 β€” THE SECOND DOOR ONTO THE SAME MONEY, guarded by the SAME
          function. It was `!!automation.running`, which is process state and therefore false for
          the entire 20-30 minute vendor wait; `runBlock` is the one definition both buttons read,
          so a fix cannot land on one and miss the other. */}
      <button type="button" className="auto-btn" disabled={busy || runState.blocked}
        title={runState.why || undefined}
        onClick={onRunNow}>
        {runState.blocked ? runState.label : "Run once now"}
      </button>
      {runState.blocked && !automation.running ? (
        <p className="auto-hint">{runState.why}</p>
      ) : null}
      {last ? (
        <>
          <p className={"autox-result is-" + (last.ok ? "ok" : "bad")}>
            {last.ok ? "Last run succeeded" : "Last run failed"}
          </p>
          <p className="auto-hint">
            {last.ts.replace("T", " ").slice(0, 16)} β€” {last.summary}
          </p>
        </>
      ) : (
        <p className="auto-hint">It has not run yet.</p>
      )}
    </>
  );
}

/**
 * ⭐ WAVE 26 Β· ITEM 9 / R11 β€” "+ New database", INSIDE the action's own database picker.
 *
 * Owner ruling R11, verbatim: *"name it and go. No dialog stack; columns follow what the action
 * writes (how the IG presets already work)."* So this is a name box and a button, in place, and
 * it selects what it creates β€” never a modal over a modal, and never a trip to another surface
 * that loses the action being configured.
 *
 * β›” IT DOES NOT INVENT THE ROW IT JUST MADE. `POST /tables` answers `{key}` alone, so the
 * component asks the caller to RE-LIST and only then selects the key. Splicing a client-built
 * `UserTable` in would put a guessed `rowCount` and an empty `fields` on screen beside real ones,
 * and the picker renders `rowCount` β€” a fabricated measurement, which is the one thing this
 * codebase refuses everywhere else.
 *
 * ⚠ THE REFUSAL IS THE SERVER'S, PRINTED VERBATIM. `POST /tables` has real refusals a person can
 * hit β€” an empty name, the `MAX_TABLES` ceiling, an unavailable store β€” and each answers with its
 * own sentence. Re-deriving "you have too many databases" here would be a second copy of a rule
 * that lives on the other side of the wall ([[schema-role-is-not-a-value-wall]]: find the line
 * that ENFORCES it, and let that line do the talking).
 */
function NewDatabase({
  disabled,
  onCreated,
}: {
  disabled: boolean;
  /**
   * Called with the new key AFTER the caller's table list has been re-read.
   * ⚠ IT MAY RETURN A PROMISE AND THE CALLER MUST AWAIT IT. Selecting the key before the list
   * contains it makes the picker's own "stored value is always an option" guard paint
   * "(not visible to you)" about the database the user just created β€” the guard doing exactly its
   * job, on a race, and saying something alarming and false.
   */
  onCreated: (key: string) => Promise<void> | void;
}) {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  const create = () => {
    const label = name.trim();
    if (!label || busy) return;
    setBusy(true);
    setErr("");
    createTable(label)
      .then(async (r) => {
        setOpen(false);
        setName("");
        // AWAITED: the caller re-reads the table list, and only then may the key be selected.
        await onCreated(r.key);
      })
      .catch((e) => {
        // The server's own words. `AutomationError` carries the composed sentence; anything else
        // is a transport failure and says so rather than blaming the name.
        setErr(
          e instanceof AutomationError && e.message
            ? e.message
            : "could not create it. The workspace did not answer"
        );
      })
      .finally(() => setBusy(false));
  };

  if (!open) {
    return (
      <button
        type="button"
        className="autoc-add"
        disabled={disabled}
        onClick={() => setOpen(true)}
      >
        + New database
      </button>
    );
  }
  return (
    <div className="autox-newdb">
      <input
        className="auto-input is-small"
        aria-label="Name for the new database"
        placeholder="Name it"
        autoFocus
        value={name}
        disabled={busy}
        onChange={(e) => setName(e.target.value)}
        // Enter creates, Escape backs out β€” the two keys a one-field form owes its user.
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            create();
          } else if (e.key === "Escape") {
            setOpen(false);
            setErr("");
          }
        }}
      />
      <button
        type="button"
        className="auto-btn is-small"
        disabled={busy || !name.trim()}
        onClick={create}
      >
        {busy ? "Creating…" : "Create"}
      </button>
      <button
        type="button"
        className="auto-btn is-small"
        disabled={busy}
        onClick={() => {
          setOpen(false);
          setErr("");
        }}
      >
        Cancel
      </button>
      {err ? <p className="autoc-bad">{err}</p> : null}
    </div>
  );
}

/**
 * ⭐⭐ WAVE 33 Β· W33-T52 (owner item 16) β€” THE WEB ACTION'S CONFIGURATION, which did not exist.
 *
 * One component for all five kinds rather than five arms, because the kinds differ ONLY in which
 * keys they carry β€” and that list already exists, once, in `WEB_SEEDS`. A per-kind arm would have
 * been a fifth place the same key set is written down, and the previous four copies are why this
 * ticket exists at all.
 *
 * β›” THE ORDER OF THE CONTROLS IS `WEB_SEEDS`' OWN KEY ORDER. Not a second list: an object literal
 * preserves insertion order in every engine this ships to, so the table that says which keys a
 * kind has also says what a person reads first. Adding a key to the seed adds its control.
 * β›” THE RED MARK IS THE SERVER'S, not this file's. `vocab.actionRequired[kind]` is
 * `ACTION_REQUIRED` on the wire β€” the same table `unconfigured_actions` and the run refusal read β€”
 * so a control marked optional here is a control the runner will start on. With no vocabulary
 * (a server older than this client) NOTHING is marked, which is the honest degradation: inventing
 * a requirement the save door does not have would refuse a step that would have run.
 * ⚠ EXPORTED for the same reason `ActionProps` is: a panel's defects (a control bound to no key,
 * two controls bound to one key, a checkbox that paints unchecked over a stored `true`) are
 * invisible to a source grep and need the real thing mounted.
 */
export function WebActionConfig({
  kind,
  cfg,
  required,
  walkFields,
  walkTable,
  busy,
  setCfg,
}: {
  kind: string;
  cfg: Record<string, unknown>;
  /** `ACTION_REQUIRED[kind]` off the wire β€” `[]` when the server did not send it. */
  required: { phrase: string; key: string }[];
  walkFields: { key: string; label: string; type: string }[];
  /** `""` when no record walks this flow β€” the R10 sentence, not an empty picker. */
  walkTable: string;
  busy: boolean;
  setCfg: (patch: Record<string, unknown>) => void;
}) {
  const shape = WEB_SEEDS[kind];
  if (!shape) return null;
  const req = new Set(required.map((r) => r.key));
  const text = (v: unknown) => (v === undefined || v === null ? "" : String(v));
  const mark = (key: string) => (req.has(key) ? <span className="autox-req">*</span> : null);

  /* Every control is UNCONTROLLED (`defaultValue` + `onBlur`), which is this file's text idiom β€”
     see the `find_records` limit box. It matters more here than there: `setCfg` merges into the
     action and re-renders the whole builder, so a controlled input would round-trip the tree on
     every keystroke of a CSS selector. */
  const line = (key: string, label: string, hint = "", mono = false) => (
    <div className="auto-field" key={key}>
      <label htmlFor={`autox-web-${key}`}>
        {mark(key)} {label}
      </label>
      <input
        id={`autox-web-${key}`}
        className={"auto-input" + (mono ? " is-mono" : "")}
        defaultValue={text(cfg[key])}
        disabled={busy}
        onBlur={(e) => setCfg({ [key]: e.target.value })}
      />
      {hint ? <p className="auto-hint">{hint}</p> : null}
    </div>
  );
  const flag = (key: string, label: string) => (
    <label className="auto-check" key={key}>
      <input
        id={`autox-web-${key}`}
        type="checkbox"
        checked={!!cfg[key]}
        disabled={busy}
        onChange={(e) => setCfg({ [key]: e.target.checked })}
      />
      {label}
    </label>
  );

  return (
    <>
      {Object.keys(shape).map((key) => {
        if (key === "url")
          /* β›” THE HINT IS PER KIND, because the answer is. `web_goto` REQUIRES an address (the
             server marks it), while the other four act on the page the journey is already on and
             an address is how you START one β€” leaving it blank is the normal case for a step that
             follows another. The first draft said "The page this step opens" on all five, which
             reads as mandatory on the four where it is not, and invites a person to paste the same
             URL into every step of a journey (found by this ticket's own verifier). */
          return line("url", "Web address",
            (kind === "web_goto"
              ? "The page this step opens."
              : "Leave this blank to act on the page the flow is already on. Fill it in only to "
                + "start somewhere new.")
            + " Braces read a column off the record this flow is walking, so {{Website}} visits a "
            + "different page for every row.");
        if (key === "waitFor")
          return line("waitFor", "Wait for this to appear first",
            "A CSS selector. The step waits for it before reporting success. Useful on a page "
            + "that fills itself in after it loads. Leave blank to not wait.", true);
        if (key === "selector")
          return line("selector", "CSS selector",
            "What on the page to act on. For example h1, .price, or #email.", true);
        if (key === "value")
          return line("value", "Value to type",
            "Braces work here too, so {{Email}} types each row's own address.");
        if (key === "hint")
          return line("hint", "What to look for",
            "Describe the thing in words. This step proposes a selector for it and writes the "
            + "proposal to the run log; it changes nothing on the page.");
        if (key === "attr")
          return line("attr", "What to take",
            "Leave this as `text` to take what a person would read. Name an attribute instead. "
            + "href, src. To take that.");
        if (key === "all") return flag("all", "Take every match, not just the first");
        if (key === "secret")
          return flag("secret", "Hide this value in the run log (for a password or a token)");
        if (key === "dryRun")
          return flag("dryRun", "Rehearse only. Find the element and report what it would do");
        if (key === "field") {
          /* β›” R10's RULE, and this key is the one place on the panel it applies. The value is a
             column on the database the flow WALKS β€” `apply_actions` writes it back onto that row β€”
             so with no walking record there is no column to choose and a picker with no options
             would read as "this database has no columns". The sentence points at the surface that
             can fix it, exactly as the condition editor below does. */
          if (!walkTable)
            return (
              <div className="auto-field" key="field">
                <label>{mark("field")} Column to write into</label>
                <p className="auto-note">
                  This flow has no record to write to β€” give it a database on the trigger
                  first.
                </p>
              </div>
            );
          const cur = text(cfg.field);
          return (
            <div className="auto-field" key="field">
              <label htmlFor="autox-web-field">{mark("field")} Column to write into</label>
              <select
                id="autox-web-field"
                className="auto-input"
                value={cur}
                disabled={busy}
                onChange={(e) => setCfg({ field: e.target.value })}
              >
                <option value="">Select a column…</option>
                {/* ⚠ THE STORED VALUE IS ALWAYS AN OPTION β€” the guard its `find_records` sibling
                    carries, and the reason it carries it: a `<select>` whose `value` matches no
                    `<option>` renders the FIRST one, so a step pointed at a column this reader
                    cannot see looks unset and the next edit writes the blank over it (D-10). */}
                {cur && !walkFields.some((f) => f.key === cur) ? (
                  <option value={cur}>{cur} (not on this database)</option>
                ) : null}
                {walkFields.map((f) => (
                  <option key={f.key} value={f.key}>
                    {f.label}
                  </option>
                ))}
              </select>
            </div>
          );
        }
        if (key === "timeoutMs")
          return (
            <div className="auto-field" key="timeoutMs">
              <label htmlFor="autox-web-timeoutMs">
                {mark("timeoutMs")} Give up after (milliseconds)
              </label>
              <input
                id="autox-web-timeoutMs"
                className="auto-input"
                type="number"
                min={WEB_TIMEOUT_MIN}
                max={WEB_TIMEOUT_MAX}
                step={1000}
                defaultValue={Number(cfg.timeoutMs) || 20000}
                disabled={busy}
                /*
                  β›” CLAMPED HERE, AND WRITTEN BACK INTO THE BOX. `min`/`max` on a number input do
                  not stop anybody TYPING 500 β€” they only decorate β€” and the server then clamps to
                  1000 on save. So a person typed 500, the box went on showing 500, and the store
                  held 1000: the panel disagreed with the store about a value the person had just
                  set, and nothing anywhere said so. Found by this ticket's own verifier, which
                  drove the real handler; the render legs were all green because the DEFAULT paints
                  correctly and only a typed out-of-range value diverges.
                  ⚠ `e.target.value = String(n)` is the half that matters. Clamping the write alone
                  would fix the store and leave the screen lying, which is the same defect with a
                  smaller blast radius. The input is uncontrolled, so React will not repaint it.
                */
                onBlur={(e) => {
                  const n = Math.min(WEB_TIMEOUT_MAX,
                    Math.max(WEB_TIMEOUT_MIN, Number(e.target.value) || 20000));
                  e.target.value = String(n);
                  setCfg({ timeoutMs: n });
                }}
              />
              <p className="auto-hint">
                Between {WEB_TIMEOUT_MIN.toLocaleString()} and {WEB_TIMEOUT_MAX.toLocaleString()}.
                Anything outside is pulled in.
              </p>
            </div>
          );
        return null;
      })}
      <p className="auto-hint">
        This step runs in a browser job of its own, which takes about 10 to 30 seconds. A run stops
        after 50 of them.
      </p>
    </>
  );
}

/**
 * ⭐ WAVE 28 β€” EXPORTED so the include-row render suite can mount the real panel.
 *
 * β›” THE EXPORT IS THE POINT, not a convenience. R6's three include rows are markup whose defect
 * modes are invisible to a source grep: a row that renders with no key attached, a Profile
 * checkbox that paints unchecked, two rows bound to the same key. `ReviewProps` below is already
 * exported for the same reason, so this is the file's existing shape rather than a new one.
 * `_test/` never ships (`deploy_web.py` excludes `_test/` and `_`-prefixed files both).
 */
export function ActionProps({
  action,
  pinned,
  catalog,
  tables,
  onTablesChanged,
  walkFields,
  walkTable,
  ops,
  nullaryOps,
  vocab,
  busy,
  onEdit,
}: {
  action: Action | null;
  /**
   * ⭐ THE PERMANENT STEP 1 OF AN INSTAGRAM SEARCH (owner report, 2026-08-06). It is the ONE
   * action whose `values` and `uniqueOn` the engine never reads: `apply_actions` drops
   * `actions[0]` for `discover_instagram` and the runner does the writing itself, upserting the
   * profile columns on `(handle, created_by)`.
   *
   * The card stays β€” "this search puts what it finds in a database" is true and worth showing β€”
   * but a `* Values` editor above `{{column_key}} reads that column off the record walking the
   * flow` is a required-looking control over a step nothing walks, and the owner spent a session
   * trying to make sense of it. Worse, it was ANSWERABLE: remapping it to `name: {{handle}}`
   * saved cleanly, changed nothing, and left the panel describing a write the engine does not
   * perform. A picture of the engine that disagrees with the engine is the defect this file
   * refuses in five other places.
   */
  pinned: boolean;
  catalog: ActionCatalogRow[];
  tables: UserTable[];
  /** ITEM 9 / R11 β€” re-read the list after this panel's picker creates one. REQUIRED; see Props. */
  onTablesChanged: () => Promise<void> | void;
  /**
   * β›” THE WALKING RECORD'S COLUMNS β€” the trigger's database, resolved by the builder.
   *
   * These three surfaces were built with `fields={[]}` and it made R3's headline feature
   * unauthorable: a conditional group's condition, an action's `when`, and `update_record`'s
   * column picker all offered "Choose a field…" and nothing else. An empty list is not a
   * neutral default here β€” it is a picker with no options, which reads as "this database has
   * no columns".
   */
  walkFields: { key: string; label: string; type: string }[];
  /**
   * ⭐ WAVE 26 Β· ITEM 5 / R10 β€” DOES A RECORD WALK THIS FLOW AT ALL? The key of the database it
   * walks, or `""`.
   *
   * β›” REQUIRED, and it answers a question `walkFields` structurally cannot. Both a flow with no
   * walking record and a flow walking an empty database hand this panel `[]`, and R10 wants
   * OPPOSITE renderings for them: a sentence pointing at the trigger for the first, an ordinary
   * (empty) picker for the second.
   * ⚠ VERIFIED AGAINST THE RUNNER, not inferred from the trigger list β€” which C4 forbids by name
   * ([[loopable-wave24]]: `CRON_DRIVEN_TRIGGERS` was exactly that mistake and became D-55).
   * `run_flow` returns immediately on `if not table_key` and otherwise walks that table's rows
   * evaluating `lane_match(act["when"], row)`, so a non-empty table key is EXACTLY the condition
   * under which `when` is ever consulted. The builder derives it from `_flow_table`'s own
   * precedence (`AutomationDetail.tsx`'s `walkTable`, whose comment carries that rule).
   */
  walkTable: string;
  ops: string[];
  nullaryOps: string[];
  vocab?: FlowVocab;
  busy: boolean;
  onEdit: (change: (a: Action) => Action) => void;
}) {
  if (!action) return <p className="auto-note">That action is no longer part of this flow.</p>;
  const row = catalog.find((c) => c.kind === action.kind);
  const cfg = action.config || {};
  const setCfg = (patch: Record<string, unknown>) =>
    onEdit((a) => ({ ...a, config: { ...a.config, ...patch } }));
  const values = (cfg as { values?: Record<string, string | number> }).values || {};
  const target = tables.find((t) => t.key === String((cfg as { table?: string }).table || ""));
  const valueFields = action.kind === "create_record" ? target?.fields || [] : walkFields;
  /**
   * The saved views of the database the flow's records WALK β€” the enrich step's optional filter.
   *
   * ⚠ Read off `walkTable`, never off `target`: `target` is the Create-record action's own
   * destination and answers a different question, and on an Instagram discovery flow the two are
   * routinely different tables. Same trap `walkFields` carries its own note about.
   * ⚠ `undefined` is a THIRD STATE and is preserved as one (`UserTable.views` is absent until the
   * server sends it) β€” the panel says "no view list was offered" rather than drawing an empty
   * picker that reads as "this database has no views".
   */
  const walkViews = (tables.find((t) => t.key === walkTable) || null)?.views;

  return (
    <>
      <h3>{row?.label || action.kind}</h3>
      {row?.detail ? <p className="auto-hint">{row.detail}</p> : null}

      <h3>Configuration</h3>

      {action.kind === "group" ? (
        <>
          {/*
            ⭐ ONE CONDITION EDITOR PER BRANCH (C-FORK). The group's own `config.cond` is GONE β€”
            a fork has a condition per leg, not one for the whole thing β€” so an editor bound to
            `cfg.cond` would now write a key `clean_actions` drops on the floor: the tree would
            look saved, survive a reload from local state, and be absent the next time anyone
            opened the automation.
            THE HEADING IS THE SERVER'S LABEL. The last leg may carry no condition, and the
            server has already named it "Otherwise" β€” giving it one here turns it into a lettered
            branch, which is a real thing to want and needs no separate control.
          */}
          {groupBranches(action).map((br, i) => (
            <div key={br.id || i}>
              <p className="auto-field-label">
                {br.label}
                {br.cond ? ". Run these actions if…" : ". Everything that reaches here"}
              </p>
              <CondBuilder
                cond={br.cond}
                onChange={(next) =>
                  onEdit((a) => ({
                    ...a,
                    config: {
                      ...a.config,
                      branches: groupBranches(a).map((x) =>
                        x.id === br.id ? { ...x, cond: next } : x
                      ),
                    },
                  }))
                }
                fields={walkFields}
                ops={ops}
                nullaryOps={nullaryOps}
                maxDepth={vocab?.maxCondDepth ?? 3}
                maxChildren={vocab?.maxCondChildren ?? 12}
                lead=""
                disabled={busy}
              />
            </div>
          ))}
          <p className="auto-hint">
            The first branch whose conditions match is the one that runs β€” the record does not go
            down two of them.
          </p>
        </>
      ) : null}

      {action.kind === "create_record" ? (
        <div className="auto-field">
          <label htmlFor="autox-atable">
            <span className="autox-req">*</span> Database
          </label>
          <select
            id="autox-atable"
            className="auto-input"
            value={String((cfg as { table?: string }).table || "")}
            disabled={busy}
            onChange={(e) => setCfg({ table: e.target.value })}
          >
            <option value="">Select a database…</option>
            {/* ⚠ THE STORED VALUE IS ALWAYS AN OPTION β€” the scar this file carries in three other
                places. A `<select>` whose `value` matches no `<option>` renders the FIRST one, so
                an action pointed at a database the reader cannot see would LOOK unset and the
                next edit would write the blank over it. */}
            {(cfg as { table?: string }).table
              && !tables.some((t) => t.key === (cfg as { table?: string }).table) ? (
              <option value={String((cfg as { table?: string }).table)}>
                {String((cfg as { table?: string }).table)} (not visible to you)
              </option>
            ) : null}
            {tables.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label}
              </option>
            ))}
          </select>
          {/* ITEM 9 / R11 β€” mint one without leaving the action being configured. */}
          <NewDatabase
            disabled={busy}
            onCreated={async (key) => {
              await onTablesChanged();
              setCfg({ table: key });
            }}
          />
          {/*
            ⭐ WAVE 25 item 4 (ruling R2b, contract C1, wiring W25-4) β€” WHAT POINTING IT HERE DOES.
            The two lists are the SERVER's (`GET /automations/presets`), diffed against whatever
            database this action names β€” R2 makes `config.table` authoritative, so a hand-made one
            answers exactly like a spawned one.
          */}
          <PresetPlan table={String((cfg as { table?: string }).table || "")} />
        </div>
      ) : null}

      {/* WHAT THE SEARCH ACTUALLY WRITES, in place of the two controls below that do not apply to
          it. ⚠ THE LIST IS `_candidate_row`'s, field for field: a shorter "the profile columns"
          would be safe and useless, and a list that drifts from what the engine writes would be
          the same lie the value map was. */}
      {pinned ? (
        <p className="auto-hint">
          The search writes one row per profile it finds β€” handle, profile link, name, followers,
          following, average engagement, bio, link in bio, verified and category β€” into that
          database. It matches on the handle, so a profile found again updates its row instead of
          adding another. There is nothing to map: the columns come from the search.
        </p>
      ) : null}

      {/*
        ⭐ WAVE 25 item 2 (ruling R1a, contract C5, wiring W25-5) β€” KEEP RECORDS UNIQUE.
        Today's Create record APPENDS FOREVER: `_commit_action_writes` mints `max(id)+1`, so any
        scheduled flow using it duplicates a row per run β€” every night, silently, until somebody
        looks at the table. `uniqueOn` names the column to upsert on instead.

        β›” `""` IS A REAL CHOICE AND IT IS THE DEFAULT, so no stored automation changes meaning the
        day this ships. That is why the empty option is worded as a behaviour ("Add a new record
        every time") rather than as an absence ("None"): it describes what will happen, which is
        the thing the reader is choosing between.

        ⚠ THE COLUMN LIST IS THE TARGET DATABASE'S, not the walking record's β€” `valueFields`
        already resolves that for `create_record`. And the server REFUSES a `uniqueOn` this action
        does not write ("it writes: …"), so the honest client move is to offer the columns it
        writes FIRST while still allowing the rest: pre-empting the refusal here would be a second
        copy of a server rule, and this file's law is that the server owns legality.
      */}
      {action.kind === "create_record" && !pinned ? (
        <div className="auto-field">
          <label htmlFor="autox-aunique">Keep records unique on</label>
          <select
            id="autox-aunique"
            className="auto-input"
            value={String((cfg as { uniqueOn?: string }).uniqueOn || "")}
            disabled={busy}
            onChange={(e) => setCfg({ uniqueOn: e.target.value })}
          >
            <option value="">Add a new record every time</option>
            {(cfg as { uniqueOn?: string }).uniqueOn
              && !valueFields.some((f) => f.key === (cfg as { uniqueOn?: string }).uniqueOn) ? (
              <option value={String((cfg as { uniqueOn?: string }).uniqueOn)}>
                {String((cfg as { uniqueOn?: string }).uniqueOn)} (not in this database)
              </option>
            ) : null}
            {valueFields.map((f) => (
              <option key={f.key} value={f.key}>
                {f.label}
              </option>
            ))}
          </select>
          <p className="auto-hint">
            {String((cfg as { uniqueOn?: string }).uniqueOn || "")
              ? "A run that finds a matching record updates it instead of adding another."
              : "Every run adds a row, even if the same one is already there."}
          </p>
        </div>
      ) : null}

      {/*
        ⭐ WAVE 25 item 1 (rulings R3/R4, contract C4) β€” THE ENRICH ACTION'S CONFIGURATION.
        It replaces the whole `field_instagram` KIND: enriching a profile is something you do TO a
        record, not a species of automation. The switches are that kind's, unchanged in meaning,
        because they are the ones that decide what a run COSTS.

        β›” NO `profileField` PICKER HERE, DELIBERATELY, and it is not an omission. C3's profile
        FLAG on the column is what binds this action (R7 β€” one flagged text field per table), and
        the server resolves it at run time; an empty `profileField` is the A3 stored-inert state,
        not an error. A second picker would let a reader choose a column the flag does not name,
        which is two sources of truth for one binding β€” and the flag is the one the engine reads.
      */}
      {isEnrich(action.kind) ? (
        <>
          {/*
            ⭐⭐ 2026-08-07 (owner ruling) β€” WHICH RECORDS THIS STEP SPENDS ON.
            Owner: *"how many records with what sort, based on a Filtered view or maybe top N
            enrichment sorted by date"*. Every enrichment is a vendor call, so an enrich step
            without this panel bills for EVERY record in the database on EVERY run β€” which is why
            these controls shipped in the same change as the fix that made the action clickable at
            all, rather than after it.

            β›” THE LIMIT IS A QUOTA OF WORK DONE, NOT A WINDOW OF ROWS READ β€” the owner's own
            clarification: *"if a user choose to enrich 30 and from that sorted list of 30, 20 is
            enriched last 30 days, then it goes to next list"*. The server walks PAST every skipped
            record until the quota is filled, so the number in this box is a cost ceiling that
            means the same thing every run. `enrich_selection` owns the rule; this panel never
            re-implements it.
          */}
          <p className="auto-field-label">Records to enrich</p>
          <div className="auto-field">
            <label htmlFor="autox-aview">From view</label>
            <select
              id="autox-aview"
              className="auto-input"
              value={String((cfg as { fromView?: string }).fromView || "")}
              disabled={busy || !walkViews}
              onChange={(e) => setCfg({ fromView: e.target.value })}
            >
              <option value="">Every record in the database</option>
              {/*
                β›”β›” D-112's SECOND CLAUSE, AND THIS PICKER WAS ACTIVELY LYING. A `<select>` whose
                `value` matches no `<option>` renders the FIRST one β€” so an enrich step bound to a
                view that no longer exists painted **"Every record in the database"**: the WIDEST
                possible reading, shown for a binding the runner refuses outright. A person looking
                at the panel saw a working automation set to enrich everything, while every run
                walked zero records; and the next edit to any other field wrote that blank over the
                stored id, destroying the only evidence of what it had been bound to.
                ⚠ MEASURED LIVE on a real tenant (D-112): `fromView` named `view_msio40hr_hu57ir`,
                which existed in NO bucket of that tenant's store, and the run reported `ok`. The
                server half now answers `partial`; this is the half a person can actually see.
                ⚠ Same guard its `find_records` and `web_read` siblings carry, for the same reason
                (D-10) β€” three pickers, one rule, because sibling surfaces written from one
                template are exactly what diverge with nothing grepping for "the other one".
              */}
              {(cfg as { fromView?: string }).fromView
                && !(walkViews || []).some((v) => v.id === (cfg as { fromView?: string }).fromView)
                ? (
                  <option value={String((cfg as { fromView?: string }).fromView)}>
                    {String((cfg as { fromView?: string }).fromView)} (this view no longer exists)
                  </option>
                ) : null}
              {(walkViews || []).map((v) => (
                <option key={v.id} value={v.id}>{v.label}</option>
              ))}
            </select>
            {/* β›” AND IT SAYS SO IN WORDS, not only as an option label. The option is what stops
                the picker lying; the sentence is what tells somebody the automation is broken and
                what to do β€” an option nobody opens the dropdown to read is a fix for the code and
                not for the person. */}
            {(cfg as { fromView?: string }).fromView && walkViews
              && !walkViews.some((v) => v.id === (cfg as { fromView?: string }).fromView) ? (
              <p className="auto-note">
                This step is bound to a view that no longer exists, so its runs walk no records.
                Pick another view, or choose every record.
              </p>
            ) : null}
            {/* ⚠ ABSENT vs EMPTY, the `UserTable.views` third state. "This server did not offer a
                view list" is a different fact from "this database has no views", and rendering an
                empty picker for the first one is the silent-empty defect wave 23 gated. */}
            {!walkViews ? (
              <p className="auto-hint">No view list was offered for that database.</p>
            ) : null}
          </div>
          <div className="auto-field">
            <label htmlFor="autox-asort">Sort by</label>
            <select
              id="autox-asort"
              className="auto-input"
              value={String((cfg as { sortField?: string }).sortField || "first_found")}
              disabled={busy}
              onChange={(e) => setCfg({ sortField: e.target.value })}
            >
              {walkFields.length === 0 ? (
                <option value="first_found">First found</option>
              ) : null}
              {walkFields.map((f) => (
                <option key={f.key} value={f.key}>{f.label}</option>
              ))}
            </select>
          </div>
          <div className="auto-field">
            <label htmlFor="autox-asortdir">Order</label>
            <select
              id="autox-asortdir"
              className="auto-input"
              value={String((cfg as { sortDir?: string }).sortDir || "desc")}
              disabled={busy}
              onChange={(e) => setCfg({ sortDir: e.target.value })}
            >
              <option value="desc">Newest / highest first</option>
              <option value="asc">Oldest / lowest first</option>
            </select>
          </div>
          <div className="auto-field">
            <label htmlFor="autox-alimit">Limit</label>
            <input
              id="autox-alimit"
              className="auto-input"
              type="number"
              min={1}
              max={100}
              defaultValue={Number((cfg as { limit?: number }).limit || 25)}
              disabled={busy}
              // Commits on blur, like `maxPosts` above and for the same reason: "3" on the way to
              // "30" is a legal number the server would happily store.
              onBlur={(e) => setCfg({ limit: Number(e.target.value) || 25 })}
            />
            <p className="auto-hint">
              Records enriched per run, at most 100. Skipped records do not use up the limit &mdash;
              the run keeps going down the list until it has enriched this many.
            </p>
          </div>
          <label className="auto-check">
            <input
              type="checkbox"
              checked={!!(cfg as { skipRecent?: boolean }).skipRecent}
              disabled={busy}
              onChange={(e) => setCfg({ skipRecent: e.target.checked })}
            />
            Skip records enriched recently
          </label>
          {/* β›” THE DAYS BOX ONLY EXISTS WHILE THE RULE IS ON. A number that configures nothing is
              worse than a missing one ([[wrong-parent-not-broken-control]]) β€” and this one would
              read as a cost guard that is running while it is switched off. */}
          {(cfg as { skipRecent?: boolean }).skipRecent ? (
            <div className="auto-field">
              <label htmlFor="autox-acool">Enriched within</label>
              <input
                id="autox-acool"
                className="auto-input"
                type="number"
                min={1}
                defaultValue={Number((cfg as { skipRecentDays?: number }).skipRecentDays || 30)}
                disabled={busy}
                onBlur={(e) => setCfg({ skipRecentDays: Number(e.target.value) || 30 })}
              />
              <p className="auto-hint">
                Days. A profile enriched inside this window is passed over, and the run moves on to
                the next one &mdash; so you never pay twice for the same profile, and the history
                still gains a point once the window closes.
              </p>
            </div>
          ) : null}

          {/*
            ⭐⭐ WAVE 28 Β· R5 / R6 / R7 β€” THE SOURCE QUESTION IS GONE, AND THREE INCLUDE AXES
            REPLACE IT. What stood here was a `Source` select writing `config.tier`
            (Anonymous / Paid provider) plus a sibling `noFallback` checkbox β€” ONE control in two
            pieces, asking the user to choose a VENDOR STRATEGY.

            β›” R5 RETIRED THE QUESTION, not just the control. Enrichment routes per capability to
            the paid providers and reports blocked on a refusal; there is no thin anonymous row to
            fall back to, so "which source" and "stop if it fails" no longer have answers a person
            could give. `tier` and `noFallback` are accepted-and-ignored in stored configs (C2,
            and D-65's law: never 400 a definition that was legal when it was written) β€” which is
            why this panel simply stops writing them rather than migrating anything.

            β›” THE ROWS BELOW ARE A TRANSFORM, NOT AN ADDITION, and that distinction is the whole
            defect risk in this change. `postMetrics` and `commentMetrics` ALREADY had checkboxes
            34 lines below this point ("Also capture per-post engagement" / "…per-comment…").
            Building three NEW rows and leaving those would have put TWO controls on each key β€”
            which compiles, renders, and satisfies any check asking whether a Post-data switch
            exists. The old pair is deleted; these carry their keys.

            ⚠ KEYS UNCHANGED ON PURPOSE (C2). Every stored enrich action round-trips untouched;
            only the labels move. R7: no cost sentence anywhere in this panel β€” the run log keeps
            honest spend reporting, and a warning printed permanently is chrome the eye stops
            reading (DESIGN.md Β§4).
          */}
          {/* ⚠ A GROUP HEADING, NOT A `<label htmlFor>`. The first cut pointed it at the Post-data
              input, which is wrong twice over: it claims one row is "the" control for a group of
              three, and clicking the heading would toggle Posts. `auto-field-label` is this
              panel's own idiom for naming a group ("Records to enrich" above uses it). */}
          <p className="auto-field-label">Include</p>
          {/* β›” DISPLAY-ONLY, AND IT IS NOT DECORATION. The profile IS the unit of enrichment β€”
              there is no run that skips it β€” so a switch here would be a control that cannot be
              off ([[wrong-parent-not-broken-control]]). It carries NO config key: rendering it
              as state would invent a flag no cleaner reads.
              ⚠ `readOnly` beside `disabled`: a `checked` input with no `onChange` is a React
              warning, and `readOnly` says the honest thing about why. */}
          <label className="auto-check">
            <input id="autox-inc-profile" type="checkbox" checked readOnly disabled />
            Profile
          </label>
          <label className="auto-check">
            <input
              id="autox-inc-posts"
              type="checkbox"
              checked={!!(cfg as { postMetrics?: boolean }).postMetrics}
              disabled={busy}
              onChange={(e) => setCfg({ postMetrics: e.target.checked })}
            />
            Post data
          </label>
          <label className="auto-check">
            <input
              id="autox-inc-comments"
              type="checkbox"
              checked={!!(cfg as { commentMetrics?: boolean }).commentMetrics}
              disabled={busy}
              onChange={(e) => setCfg({ commentMetrics: e.target.checked })}
            />
            Comment data
          </label>
          {/*
            ⭐ WAVE 26 Β· ITEM 7 / R2 + C5 β€” TWO CONTROLS, AND THEY ARE INDEPENDENT.
            R2 splits them deliberately: how many posts to KEEP is FREE and rides the profile
            pull, while per-post engagement is a SEPARATE, PAID scrape (one extra vendor record
            per post per run β€” roughly 13x). They were nested here, so the free control was only
            reachable by first switching the paid one on: a person who wanted 5 posts instead of
            24 had to agree to buy engagement metrics to say so.
          */}
          <div className="auto-field">
            <label htmlFor="autox-aposts">Posts per profile</label>
            <input
              id="autox-aposts"
              className="auto-input"
              type="number"
              min={1}
              /* β›” 12, AND IT IS THE VENDOR'S β€” MEASURED, not a policy we chose (C5, and
                 `automation_engine.py:2165`: a Profiles row carries the TOP 12, "a cap, not a
                 count"). It read 200. `clean_max_posts` REFUSES a value the panel SENT above the
                 cap, so the old box could produce a 400 by typing a number it invited. */
              max={12}
              /* ⚠ 10, NOT 24 β€” the same number twice over. `DEFAULT_POSTS_PER_PULL` is 10, and 24
                 is now ABOVE the ceiling, so an empty box used to fall back to a value the save
                 door refuses. [[default-must-pass-its-own-guard]]: a law added later turns
                 yesterday's safe default into a value the product rejects. */
              defaultValue={Number((cfg as { maxPosts?: number }).maxPosts || 10)}
              disabled={busy}
              // FREE TEXT COMMITS ON BLUR β€” per-keystroke would PATCH a half-typed number, and
              // "2" on the way to "24" is a legal value the server would happily store.
              onBlur={(e) => setCfg({ maxPosts: Number(e.target.value) || 10 })}
            />
            <p className="auto-hint">
              At most 12 β€” the provider returns a profile&rsquo;s top 12 posts and no more.
            </p>
          </div>
          {/*
            ⭐⭐ W29-T09 (owner item 11: *"the last 12 reels"*) β€” THE ONLY DOOR TO `config.postGroups`.
            The server side has been whole since wave 28 β€” `clean_post_groups` validates it, the
            enrich runner applies it β€” and `postGroups` had **zero occurrences** anywhere in
            `web/src`, so NO USER COULD ASK FOR REELS-ONLY AT ALL. That is why this is a blocker for
            the reels routing work and not a nicety: those tickets' negative controls need a config
            a person can actually produce.

            β›” THE KEYS ARE THE SERVER'S AND SO ARE THE WORDS. `vocab.postTypes` carries both; a
            client that translated `video` into "Reels" locally would be a second copy of a
            vocabulary `clean_post_groups` refuses deviations from. Absent vocabulary renders
            NOTHING rather than three guessed names.

            β›” ABSENT IS OFF, AND OFF IS THE DEFAULT FOREVER. An enrich action stored before this
            control carries no `postGroups`, and the runner returns the post list unchanged when the
            key is missing β€” so unchecking every box must DELETE the key, never store `[]`-with-
            meaning or a group of zero. Deleting it is what keeps an old automation capturing
            exactly what it always captured.

            ⚠ ONE WRITER FOR ONE KEY [W-12]. This is the only control in `web/src` that writes
            `postGroups`; the `maxPosts` box above writes `maxPosts` and nothing else. The two are
            related only in that a group cannot keep more posts than the pull captures β€” which is
            the server's rule, printed here rather than re-implemented.
          */}
          {(vocab?.postTypes || []).length ? (
            <div className="auto-field">
              <p className="auto-field-label">Keep only certain posts</p>
              {(vocab?.postTypes || []).map((pt) => {
                const groups =
                  ((cfg as { postGroups?: { type: string; limit: number }[] }).postGroups) || [];
                const mine = groups.find((g) => g && g.type === pt.key);
                const cap = Math.max(
                  1,
                  Number((cfg as { maxPosts?: number }).maxPosts || 10) || 10
                );
                /* β›” WRITE THROUGH ONE FUNCTION, so the "no groups left β‡’ remove the key" rule
                   exists once. Two call sites each deciding it is how `[]` starts meaning
                   "capture nothing". */
                const write = (next: { type: string; limit: number }[]) =>
                  setCfg({ postGroups: next.length ? next : undefined });
                return (
                  <label className="auto-check" key={pt.key}>
                    <input
                      type="checkbox"
                      checked={!!mine}
                      disabled={busy}
                      onChange={(e) =>
                        write(
                          e.target.checked
                            ? [...groups.filter((g) => g.type !== pt.key),
                               { type: pt.key, limit: Math.min(cap, 12) }]
                            : groups.filter((g) => g.type !== pt.key)
                        )
                      }
                    />
                    {pt.label}
                    {mine ? (
                      <input
                        className="auto-input auto-input-inline"
                        type="number"
                        min={1}
                        max={cap}
                        aria-label={`How many ${pt.label} to keep`}
                        /* Commits on BLUR, exactly like `maxPosts` above and for the identical
                           reason: "1" on the way to "12" is a value the server would store. */
                        defaultValue={mine.limit}
                        disabled={busy}
                        onBlur={(e) =>
                          write([
                            ...groups.filter((g) => g.type !== pt.key),
                            {
                              type: pt.key,
                              limit: Math.max(1, Number(e.target.value) || 1),
                            },
                          ])
                        }
                      />
                    ) : null}
                  </label>
                );
              })}
              <p className="auto-hint">
                Leave these unticked to keep every post. Ticked, only the kinds you name are
                kept β€” and a group cannot keep more than the {" "}
                {Number((cfg as { maxPosts?: number }).maxPosts || 10) || 10} posts this
                enrichment captures.
              </p>
            </div>
          ) : null}
          {/*
            ⭐ WAVE 28 Β· R6/R7 β€” THE TWO CHECKBOXES THAT STOOD HERE MOVED UP INTO THE INCLUDE
            GROUP, KEYS AND ALL (`postMetrics`, `commentMetrics`). They are not deleted features:
            they are the SAME two switches, relabelled "Post data" and "Comment data" and grouped
            with the always-on Profile row so the three capture axes read as one decision.
            β›” THEIR CONDITIONAL COST HINTS WENT WITH THEM AND DID NOT COME BACK (R7): "Billed per
            post, not per profile" and "Billed by the separate Comments dataset". R7 puts spend
            reporting in the RUN LOG, where it is a measured fact about work already done, rather
            than in the panel, where it was a permanent caption on a switch.
            ⚠ Leaving them here as well as above is the duplicate-writer trap this wave's item 1
            was one literal reading away from shipping β€” two controls on one key, both correct,
            neither authoritative.
          */}
          <label className="auto-check">
            <input
              type="checkbox"
              checked={!!(cfg as { dryRun?: boolean }).dryRun}
              disabled={busy}
              onChange={(e) => setCfg({ dryRun: e.target.checked })}
            />
            Dry run β€” read and report, write nothing
          </label>
        </>
      ) : null}

      {(action.kind === "update_record" || action.kind === "create_record") && !pinned ? (
        <>
          <p className="auto-field-label">
            <span className="autox-req">*</span> Values
          </p>
          {Object.entries(values).map(([key, val], i) => (
            <div className="autoc-row" key={i}>
              <button
                type="button"
                className="autoc-drop"
                disabled={busy}
                aria-label="Remove this value"
                onClick={() => {
                  const next = { ...values };
                  delete next[key];
                  setCfg({ values: next });
                }}
              >
                <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
                  <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                    strokeLinecap="round" />
                </svg>
              </button>
              <select
                className="auto-input is-tiny"
                value={key}
                disabled={busy}
                aria-label="Column"
                onChange={(e) => {
                  const next: Record<string, string | number> = {};
                  for (const [k, v] of Object.entries(values))
                    next[k === key ? e.target.value : k] = v;
                  setCfg({ values: next });
                }}
              >
                <option value="">Choose a column…</option>
                {/* ⚠ WHICH RECORD'S COLUMNS depends on the action: `create_record` writes into
                    the database it NAMES, `update_record` writes onto the record walking the
                    flow β€” the trigger's. Offering the target's columns for both would list the
                    wrong database's columns for every update action. */}
                {key && !valueFields.some((f) => f.key === key) ? (
                  <option value={key}>{key}</option>
                ) : null}
                {valueFields.map((f) => (
                  <option key={f.key} value={f.key}>
                    {f.label}
                  </option>
                ))}
              </select>
              <input
                className="auto-input is-tiny autoc-value"
                defaultValue={String(val ?? "")}
                disabled={busy}
                aria-label="Value"
                placeholder="Value or {{column}}"
                onBlur={(e) => setCfg({ values: { ...values, [key]: e.target.value } })}
              />
            </div>
          ))}
          <button
            type="button"
            className="autoc-add"
            disabled={busy}
            onClick={() => setCfg({ values: { ...values, "": "" } })}
          >
            + Add a value
          </button>
          {/* ⭐ THE SENTENCE THE OWNER COULD NOT PARSE, 2026-08-06. `{{column_key}}` is a
              PLACEHOLDER standing for a placeholder, and "the record walking the flow" is this
              module's internal noun for the row a step is currently running on β€” two layers of
              indirection in eleven words, above a box the reader is already unsure how to fill.
              It says what to TYPE, using a column this database actually has, and names the two
              choices as choices. `walkFields` is the walking record's columns for both action
              kinds, which is what a placeholder resolves against. */}
          <p className="auto-hint">
            Type a fixed value, or{" "}
            <code>{`{{${walkFields[0]?.key || "column"}}}`}</code> to copy{" "}
            {walkFields[0]?.label ? <>β€œ{walkFields[0].label}”</> : "a column"} from the record this
            step is running on.
          </p>
        </>
      ) : null}

      {action.kind === "find_records" ? (
        <>
          <div className="auto-field">
            <label htmlFor="autox-ftable">
              <span className="autox-req">*</span> Database
            </label>
            <select
              id="autox-ftable"
              className="auto-input"
              value={String((cfg as { table?: string }).table || "")}
              disabled={busy}
              onChange={(e) => setCfg({ table: e.target.value })}
            >
              <option value="">Select a database…</option>
              {/* ⚠ THE STORED VALUE IS ALWAYS AN OPTION β€” the same scar its `create_record`
                  sibling carries three lines up, and this picker did NOT have the guard. A
                  `<select>` whose `value` matches no `<option>` renders the FIRST one, so a
                  find_records pointed at a database this reader cannot see looked unset, and the
                  next edit wrote the blank over it. Sibling surfaces written from one template
                  diverge exactly this way and nothing greps for "the other one" (D-10). */}
              {(cfg as { table?: string }).table
                && !tables.some((t) => t.key === (cfg as { table?: string }).table) ? (
                <option value={String((cfg as { table?: string }).table)}>
                  {String((cfg as { table?: string }).table)} (not visible to you)
                </option>
              ) : null}
              {tables.map((t) => (
                <option key={t.key} value={t.key}>
                  {t.label}
                </option>
              ))}
            </select>
            {/* ITEM 9 / R11 β€” "every action's database picker", so this one too. */}
            <NewDatabase
              disabled={busy}
              onCreated={async (key) => {
                await onTablesChanged();
                setCfg({ table: key });
              }}
            />
          </div>
          <p className="auto-field-label">Conditions</p>
          <CondBuilder
            cond={(cfg as { cond?: Cond | null }).cond || null}
            onChange={(next) => setCfg({ cond: next })}
            fields={target?.fields || []}
            ops={ops}
            nullaryOps={nullaryOps}
            maxDepth={vocab?.maxCondDepth ?? 3}
            maxChildren={vocab?.maxCondChildren ?? 12}
            disabled={busy}
          />
          <div className="auto-field">
            <label htmlFor="autox-flimit">How many at most</label>
            <input
              id="autox-flimit"
              className="auto-input"
              type="number"
              min={1}
              defaultValue={Number((cfg as { limit?: number }).limit || 25)}
              disabled={busy}
              onBlur={(e) => setCfg({ limit: Number(e.target.value) || 25 })}
            />
          </div>
          <p className="auto-hint">
            What it found opens from the run log. Piping the rows into a later step is not built
            yet.
          </p>
        </>
      ) : null}

      {/* ⭐⭐ W33-T52 (owner item 16) β€” the five web kinds, which had NO arm here at all. See
          `WebActionConfig`. It is one component rather than five arms because the kinds differ
          only in which keys they carry, and that list lives in `WEB_SEEDS`. */}
      {/* ⭐⭐ W33-T56 (R3) β€” the fuzzy step's configuration. Three controls and a ceiling: where to
          start, what to do in words, and where to put the answer. Deliberately NOT routed through
          `WebActionConfig`: that component walks `WEB_SEEDS`, and sharing it would mean adding
          `ai_agent` to a table the browser job's runner does not implement. */}
      {action.kind === "ai_agent" ? (
        <>
          <div className="auto-field">
            <label htmlFor="autox-ai-url">
              <span className="autox-req">*</span> Start on this page
            </label>
            <input
              id="autox-ai-url"
              className="auto-input"
              defaultValue={String((cfg as { url?: string }).url || "")}
              disabled={busy}
              onBlur={(e) => setCfg({ url: e.target.value })}
            />
            <p className="auto-hint">
              Braces read a column off the record this flow is walking, so {"{{Website}}"} starts
              somewhere different for every row.
            </p>
          </div>
          <div className="auto-field">
            <label htmlFor="autox-ai-instruction">
              <span className="autox-req">*</span> What to do there
            </label>
            <textarea
              id="autox-ai-instruction"
              className="auto-input"
              rows={3}
              defaultValue={String((cfg as { instruction?: string }).instruction || "")}
              disabled={busy}
              onBlur={(e) => setCfg({ instruction: e.target.value })}
            />
            <p className="auto-hint">
              Plain words. The assistant works out the clicks and the selectors when the flow runs,
              against the page as it is that day, and the run log lists every step it took.
            </p>
          </div>
          {/* The column is OPTIONAL here and required on `web_read`, and the difference is real: a
              journey may only need to have been performed. Same picker and the same R10 sentence
              as its sibling, so the two cannot look like different controls. */}
          {!walkTable ? (
            <div className="auto-field">
              <label>Column to write the answer into</label>
              <p className="auto-note">
                This flow has no record to write to β€” give it a database on the trigger first.
              </p>
            </div>
          ) : (
            <div className="auto-field">
              <label htmlFor="autox-ai-field">Column to write the answer into</label>
              <select
                id="autox-ai-field"
                className="auto-input"
                value={String((cfg as { field?: string }).field || "")}
                disabled={busy}
                onChange={(e) => setCfg({ field: e.target.value })}
              >
                <option value="">Do not write anything</option>
                {(cfg as { field?: string }).field
                  && !walkFields.some((f) => f.key === (cfg as { field?: string }).field) ? (
                  <option value={String((cfg as { field?: string }).field)}>
                    {String((cfg as { field?: string }).field)} (not on this database)
                  </option>
                ) : null}
                {walkFields.map((f) => (
                  <option key={f.key} value={f.key}>
                    {f.label}
                  </option>
                ))}
              </select>
            </div>
          )}
          <div className="auto-field">
            <label htmlFor="autox-ai-maxsteps">At most this many steps</label>
            <input
              id="autox-ai-maxsteps"
              className="auto-input"
              type="number"
              min={1}
              max={AI_AGENT_MAX_STEPS}
              defaultValue={Number((cfg as { maxSteps?: number }).maxSteps) || 6}
              disabled={busy}
              onBlur={(e) => {
                // Clamped and painted back, the same rule the web timeout box learned: `min`/`max`
                // decorate a number input, they do not stop anybody typing past them.
                const n = Math.min(AI_AGENT_MAX_STEPS, Math.max(1, Number(e.target.value) || 6));
                e.target.value = String(n);
                setCfg({ maxSteps: n });
              }}
            />
            <p className="auto-hint">
              Each step is a real browser action. The ceiling is {AI_AGENT_MAX_STEPS}.
            </p>
          </div>
          <label className="auto-check">
            <input
              id="autox-ai-dryrun"
              type="checkbox"
              checked={!!(cfg as { dryRun?: boolean }).dryRun}
              disabled={busy}
              onChange={(e) => setCfg({ dryRun: e.target.checked })}
            />
            Rehearse only β€” find the elements and report, change nothing
          </label>
        </>
      ) : null}

      {isWeb(action.kind) ? (
        <WebActionConfig
          kind={action.kind}
          cfg={cfg as Record<string, unknown>}
          required={vocab?.actionRequired?.[action.kind] || []}
          walkFields={walkFields}
          walkTable={walkTable}
          busy={busy}
          setCfg={setCfg}
        />
      ) : null}

      {/*
        ⭐ WAVE 26 Β· ITEM 5 β€” OWNER RULINGS R9 AND R10, and they are two different fixes to one
        symptom (*"the condition on action act_1 names no field"*).

        R9 β€” A `create_record` HAS NO CONDITIONS AT ALL. The owner corrected their own first
        answer mid-grill: *"if it is Create Record, I don't think you can even add Conditions at
        all. That's not how the Create Record works."* Airtable agrees and so does the shape:
        every other action operates ON the record the flow is walking, so "run this only when
        <that record> …" is a question about something that exists. Create record MAKES one.
        There is nothing to test yet β€” which is why the picker on this panel was always empty and
        why every condition saved against it named no field.
        β›” THE SERVER DROPS A STORED `when` RATHER THAN REFUSING IT (C4), and this removal is what
        makes that silent drop defensible: `clean_actions` has no disclosure channel, so the drop
        is only safe while there is no control whose value could appear to be ignored. Deleting
        the editor and dropping the value are ONE change in two files β€” if this editor ever comes
        back for `create_record`, the drop becomes silent data loss (booked by A).

        R10 β€” NO WALKING RECORD β‡’ A SENTENCE, NEVER AN EMPTY PICKER. A picker with no options
        reads as "this database has no columns", and anything saved through it names no field,
        which is the refusal the owner kept meeting. The sentence points at the surface that CAN
        answer: the trigger.
        ⚠ The test is `walkTable`, not `walkFields.length` β€” see the prop's own note. A flow
        walking a database that genuinely has no columns yet keeps its (empty) picker, because
        for that flow the picker is the right control and adding a column is the fix.
      */}
      {action.kind === "create_record" ? null : !walkTable ? (
        <>
          <h3>Run this only when</h3>
          <p className="auto-note">
            This flow has no record to test β€” set conditions on the trigger instead.
          </p>
        </>
      ) : (
        <>
          <h3>Run this only when</h3>
          <CondBuilder
            cond={action.when || null}
            onChange={(next) => onEdit((a) => ({ ...a, when: next }))}
            fields={walkFields}
            ops={ops}
            nullaryOps={nullaryOps}
            maxDepth={vocab?.maxCondDepth ?? 3}
            maxChildren={vocab?.maxCondChildren ?? 12}
            disabled={busy}
          />
          {!condComplete(action.when || null, nullaryOps) ? null : (
            <p className="auto-hint">Leave empty to run it every time.</p>
          )}
        </>
      )}
    </>
  );
}

export function ReviewProps({
  cfg,
  vocab,
  busy,
  setCfg,
}: {
  cfg: Record<string, unknown>;
  vocab?: FlowVocab;
  busy: boolean;
  setCfg: (patch: Record<string, unknown>) => void;
}) {
  const by = String(cfg.decidedBy || "user");
  const next = Array.isArray(cfg.next) ? (cfg.next as string[]) : [];
  const aiReady = vocab?.aiReady !== false;
  return (
    <>
      <div className="auto-field">
        <label htmlFor="autox-rby">Decided by</label>
        <select
          id="autox-rby"
          className="auto-input"
          value={by}
          disabled={busy}
          onChange={(e) => setCfg({ decidedBy: e.target.value })}
        >
          {(vocab?.reviewDeciders || ["user"]).map((d) => (
            <option key={d} value={d}>
              {d === "ai" ? "AI" : "A person"}
            </option>
          ))}
        </select>
      </div>
      {/*
        ⚠ `aiReady` IS A MEASUREMENT OF THIS DEPLOYMENT, and it is stated rather than styled
        around. With no LLM key the engine holds every card for a human β€” so an AI review that
        looked configured would promise a decision nothing will make (C6's fail-closed path).
      */}
      {by === "ai" && !aiReady ? (
        <p className="auto-note">
          No AI provider is configured here, so these cards wait for a person.
        </p>
      ) : null}
      {by === "ai" ? (
        <div className="auto-field">
          <label htmlFor="autox-rprompt">What should it decide?</label>
          <textarea
            id="autox-rprompt"
            className="auto-input"
            rows={3}
            defaultValue={String(cfg.prompt || "")}
            disabled={busy}
            placeholder="Approve suppliers with a UK address and more than 20 reviews."
            onBlur={(e) => setCfg({ prompt: e.target.value })}
          />
        </div>
      ) : null}
      <div className="auto-field">
        <label htmlFor="autox-rlabel">Stage name</label>
        <input
          id="autox-rlabel"
          className="auto-input"
          defaultValue={String(cfg.label || "Review")}
          disabled={busy}
          onBlur={(e) => setCfg({ label: e.target.value })}
        />
      </div>
      <p className="auto-field-label">Where it can go next</p>
      {next.map((n, i) => (
        <div className="autoc-row" key={i}>
          <button
            type="button"
            className="autoc-drop"
            disabled={busy}
            aria-label={`Remove ${n}`}
            onClick={() => setCfg({ next: next.filter((_x, j) => j !== i) })}
          >
            <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
                strokeLinecap="round" />
            </svg>
          </button>
          <input
            className="auto-input is-tiny"
            defaultValue={n}
            disabled={busy}
            aria-label="Stage this review can send a record to"
            onBlur={(e) =>
              setCfg({ next: next.map((x, j) => (j === i ? e.target.value : x)) })
            }
          />
        </div>
      ))}
      <button
        type="button"
        className="autoc-add"
        disabled={busy}
        onClick={() => setCfg({ next: [...next, ""] })}
      >
        + Add an exit
      </button>
      <p className="auto-hint">
        Each exit is a lane on the board. A card waits here until it is moved to one of them.
      </p>
    </>
  );
}