aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/static/intereditor.js
blob: 3928299ec01485e56d7bce0c00cd0ef6429a2a04 (plain)
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
// intereditor.js — Structured condition & step editors for trigger blocks.
// Drives the unified Trigger model:
//   Trigger = { lock, item_id?, condition?, steps[], on_player_flag?, on_global_flag?, value? }
//   Step    = { condition?, wait, messages[], broadcast, broadcast_global,
//               spawn_mob, despawn_mob, set_global_flags, set_player_flags,
//               give_item, take_item, teleport, heal, credits, aps_node,
//               drop_table[] }
// Shared by objecteditor.js, mobeditor.js, and map.js.

// ── Condition leaf types ──

var IE_COND_TYPES = [
  {type: 'global_flag', label: 'Global Flag', hint: 'global flag name'},
  {type: 'player_flag', label: 'Player Flag', hint: 'player flag name'},
  {type: 'room',        label: 'In Room',     hint: 'room ID'},
  {type: 'has_item',    label: 'Has Item',    hint: 'item ID'},
  {type: 'min_credits', label: 'Min Credits', hint: 'amount'},
];

// ── Effect field types ──
//
// Every block is sequence-scoped now: broadcast / broadcast_global /
// spawn_mob / despawn_mob are available everywhere. Messages and condition
// are handled separately (plain-string message rows; per-step condition).

var IE_ACT_TYPES = [
  {key: 'wait',              label: 'Wait',             kind: 'number',  hint: 'ticks before this step'},
  {key: 'broadcast',         label: 'Broadcast',         kind: 'text',    hint: '%p = player'},
  {key: 'broadcast_global', label: 'Broadcast Global',  kind: 'text',    hint: '%p = player'},
  {key: 'spawn_mob',         label: 'Spawn Mob',         kind: 'search',  entity: 'mobs'},
  {key: 'despawn_mob',       label: 'Despawn Mob',       kind: 'search',  entity: 'mobs'},
  {key: 'set_global_flags',  label: 'Set Global Flags',  kind: 'kv'},
  {key: 'set_player_flags',  label: 'Set Player Flags',  kind: 'kv'},
  {key: 'give_item',         label: 'Give Item',         kind: 'search',  entity: 'items'},
  {key: 'take_item',         label: 'Take Item',         kind: 'search',  entity: 'items'},
  {key: 'drop_table',        label: 'Drop Table',        kind: 'droptable'},
  {key: 'teleport',          label: 'Teleport',          kind: 'number',  hint: 'room ID'},
  {key: 'heal',              label: 'Heal',              kind: 'number',  hint: 'HP to restore'},
  {key: 'credits',           label: 'Credits',           kind: 'number',  hint: 'amount (negative = cost)'},
  {key: 'aps_node',          label: 'APS Node',          kind: 'checkbox'},
];

// ── Step-kind buttons for the bottom add-bar (each click creates a new
//     step initialised with that single action kind) and the per-step
//     "+" toggle bar.  messages is handled separately from IE_ACT_TYPES. ──

var IE_STEP_KINDS = [
  {key: 'messages',         label: 'Message',         kind: 'messages'},
];
IE_ACT_TYPES.forEach(function(at) {
  IE_STEP_KINDS.push(at);
});

// ── Scope / Context system ──
// Lets condition & action editors target data models outside the
// default ed[secPath][idx].steps[si] arrangement (e.g. talk node/option
// conditions and single-step actions). When a scope is registered and its
// token is placed on a DOM root via data-ie-scope, all mutation onclicks
// resolve their data target through the scope instead of the legacy trigger
// path.

window._ieScopes = {};
var _ieScopeSeq = 0;

function ie_registerScope(opts, token) {
  if (!token) {
    token = 'sc' + (++_ieScopeSeq);
  }
  window._ieScopes[token] = opts;
  return token;
}
window.ie_registerScope = ie_registerScope;

function ie_unregisterScope(token) {
  delete window._ieScopes[token];
}
window.ie_unregisterScope = ie_unregisterScope;

function _ie_scopeFromEl(el) {
  if (!el || !el.closest) return null;
  var scopeEl = el.closest('[data-ie-scope]');
  if (!scopeEl) return null;
  var token = scopeEl.getAttribute('data-ie-scope');
  return window._ieScopes[token] || null;
}

// Resolve the .ie-cond-root DOM element scoped to a mutation element el.
// Handles both the root itself and the outer addbar (which sits outside
// .ie-cond-root as a sibling).
function _ie_condScopeRoot(el) {
  var root = el.closest('.ie-cond-root');
  if (root) return root;
  var addbar = el.closest('.ie-cond-addbar');
  if (!addbar) return null;
  var parent = addbar.parentElement;
  if (!parent) return null;
  return parent.querySelector('.ie-cond-root');
}

// Unified condition-editing context.
// Returns { get, set, change } — `get` always syncs DOM → data store
// before returning. Routes through a registered scope when el lives inside
// [data-ie-scope], otherwise through the legacy ed[secPath][idx] trigger path.
function _ie_condCtx(el, secId, secPath, idx, kind) {
  var scope = _ie_scopeFromEl(el);
  if (scope) {
    return {
      get: function() {
        var root = _ie_condScopeRoot(el);
        if (root) {
          var cond = ie_collectCond(root);
          scope.setCond(cond);
        }
        return scope.getCond();
      },
      set: function(c) { scope.setCond(c); },
      change: function() { scope.onChange(); }
    };
  }
  return {
    get: function() {
      var ed = window._editorData;
      if (!ed) return null;
      _ie_syncCond(ed, secId, secPath, idx, kind);
      return _ie_getCond(ed, secPath, idx, kind);
    },
    set: function(c) {
      var ed = window._editorData;
      if (!ed) return;
      _ie_setCond(ed, secPath, idx, kind, c);
      ced_syncDOMToData(ed);
    },
    change: function() { window._ieRenderOnly(); }
  };
}

// Unified action/step-editing context.
// Returns { get, set, change }.  In scope mode reads the .ie-act-root
// container; in legacy mode operates on ed[secPath][idx].steps[si].
function _ie_actCtx(el, secId, secPath, idx, si) {
  var scope = _ie_scopeFromEl(el);
  if (scope) {
    return {
      get: function() {
        var container = el.closest('.ie-act-root');
        if (!container) return scope.getStep() || {};
        var act = ie_collectAct(container);
        var msgs = ie_collectMessages(container);
        var step = scope.getStep() || {};
        if (act) Object.keys(act).forEach(function(k) { step[k] = act[k]; });
        if (msgs !== null) step.messages = msgs; else delete step.messages;
        scope.setStep(step);
        return scope.getStep();
      },
      set: function(s) { scope.setStep(s); },
      change: function() { scope.onChange(); }
    };
  }
  return {
    get: function() {
      var ed = window._editorData;
      if (!ed) return {};
      ie_syncStep(ed, secId, secPath, idx, si);
      if (!ed[secPath] || !ed[secPath][idx] || !ed[secPath][idx].steps || !ed[secPath][idx].steps[si]) return {};
      return ed[secPath][idx].steps[si];
    },
    set: function(s) {
      var ed = window._editorData;
      if (!ed) return;
      if (!ed[secPath]) ed[secPath] = [];
      if (!ed[secPath][idx]) ed[secPath][idx] = {steps: []};
      if (!ed[secPath][idx].steps) ed[secPath][idx].steps = [];
      ed[secPath][idx].steps[si] = s;
      ced_syncDOMToData(ed);
    },
    change: function() { window._ieRenderOnly(); }
  };
}

// ── Rendering helpers ──

// ie_renderStepAddbar: the per-step action add bar revealed by the "+" toggle.
// Only shows kinds not already present on this step.
function ie_renderStepAddbar(step, secId, idx, si, secPath) {
  var h = '';
  IE_STEP_KINDS.forEach(function(sk) {
    if (sk.key === 'messages') {
      if (step && Array.isArray(step.messages)) return;
    } else {
      if (step && Object.prototype.hasOwnProperty.call(step, sk.key)) {
        if (sk.kind === 'checkbox' && step[sk.key] !== true) { /* re-addable */ }
        else return;
      }
    }
    if (sk.key === 'messages') {
      h += '<button class="btn btn-sm ie-add-btn" onclick="ie_addMessages(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ')">+ ' + esc(sk.label) + '</button>';
    } else {
      h += '<button class="btn btn-sm ie-add-btn" onclick="ie_addActEffect(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(sk.key) + '\')">+ ' + esc(sk.label) + '</button>';
    }
  });
  return h;
}

// ie_renderBottomAddbar: the always-visible bar at the foot of the step list.
// Each button creates a new step initialised with that single action kind.
function ie_renderBottomAddbar(secId, secPath, idx) {
  var h = '';
  IE_STEP_KINDS.forEach(function(sk) {
    h += '<button class="btn btn-sm ie-add-btn" onclick="ie_addStepKind(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(sk.key) + '\')">+ ' + esc(sk.label) + '</button>';
  });
  return h;
}

// ── Drop Table block renderer (shared between intereditor and triggerseditor) ──

function ie_renderDropTableBlock(drops, onAddItem, onAddTable, onRemove) {
  drops = drops || [];
  var h = '<div class="ie-drop-table">';
  drops.forEach(function(row, ri) {
    var kind = row.table ? 'table' : (row.item_id ? 'item' : (row._kind || 'item'));
    h += '<div class="ie-drop-row">';
    if (kind === 'table') {
      h += '<div class="obj-search" style="position:relative;min-width:0;flex:2"><input class="search-input ie-drop-table-input" data-search-type="drops" value="' + escAttr(row.table || '') + '" placeholder="Table ID"><div class="search-results" style="display:none"></div></div>';
    } else {
      h += '<div class="obj-search" style="position:relative;min-width:0;flex:2"><input class="search-input ie-drop-item-input" data-search-type="items" value="' + escAttr(row.item_id || '') + '" placeholder="Item ID"><div class="search-results" style="display:none"></div></div>';
    }
    h += '<input class="ie-drop-weight" type="number" value="' + (row.weight || 10) + '" placeholder="Weight" style="width:60px" min="0">';
    h += '<input class="ie-drop-qty" type="number" value="' + (row.quantity || 1) + '" placeholder="Qty" style="width:50px" min="0">';
    h += '<button class="btn btn-sm btn-danger" onclick="' + onRemove.replace(/__RI__/g, String(ri)) + '">X</button>';
    h += '</div>';
  });
  h += '<div style="display:flex;gap:6px;margin-top:4px">';
  h += '<button class="btn btn-sm obj-sub-add" onclick="' + onAddItem + '">+ Add Item</button>';
  h += '<button class="btn btn-sm obj-sub-add" onclick="' + onAddTable + '">+ Add Table</button>';
  h += '</div>';
  h += '</div>';
  return h;
}

function ie_collectDropTableBlock(container) {
  if (!container) return null;
  var rows = container.querySelectorAll(':scope > .ie-drop-row');
  var out = [];
  rows.forEach(function(row) {
    var tableInput = row.querySelector('.ie-drop-table-input');
    var itemInput = row.querySelector('.ie-drop-item-input');
    var weightInput = row.querySelector('.ie-drop-weight');
    var qtyInput = row.querySelector('.ie-drop-qty');
    var entry = {};
    if (tableInput && tableInput.value.trim()) {
      entry.table = tableInput.value.trim();
      entry._kind = 'table';
    } else if (itemInput && itemInput.value.trim()) {
      entry.item_id = itemInput.value.trim();
      entry._kind = 'item';
    } else if (itemInput) {
      entry.item_id = '';
      entry._kind = 'item';
    } else {
      entry.table = '';
      entry._kind = 'table';
    }
    entry.weight = weightInput ? (parseInt(weightInput.value, 10) || 0) : 0;
    entry.quantity = qtyInput ? (parseInt(qtyInput.value, 10) || 0) : 0;
    out.push(entry);
  });
  return out.length > 0 ? out : null;
}

// ie_addStepKind creates a new step initialised with a single action kind.
function ie_addStepKind(el, secId, secPath, idx, kind) {
  var ed = window._editorData;
  if (!ed) return;
  ced_syncDOMToData(ed);
  if (window._ieSyncAll) window._ieSyncAll(ed);
  if (!ed[secPath]) ed[secPath] = [];
  if (!ed[secPath][idx]) ed[secPath][idx] = {};
  if (!ed[secPath][idx].steps || !Array.isArray(ed[secPath][idx].steps)) ed[secPath][idx].steps = [];
  var step = {};
  if (kind === 'messages') {
    step.messages = [''];
  } else if (kind === 'wait') {
    step.wait = 1;
  } else {
    var at = IE_ACT_TYPES.find(function(a) { return a.key === kind; });
    if (!at) return;
    if (at.kind === 'kv') step[kind] = {};
    else if (at.kind === 'checkbox') step[kind] = true;
    else if (at.kind === 'number') step[kind] = 0;
    else if (at.kind === 'droptable') step[kind] = [];
    else step[kind] = '';
  }
  ed[secPath][idx].steps.push(step);
  window._ieRenderCurrent();
}

// Sentinel child-index for a root-level single leaf (no parent group).
var IE_ROOT_LEAF = -1;

// ── Condition lens helpers (entry vs step) ──
//
// kind is the string-encoded condition anchor: 'entry' for the trigger's own
// condition, or 'step-<n>' for the nth step's condition. Internally we parse
// it to the numeric step index (-1 = entry).

function _ie_kindStep(kind) {
  if (kind === undefined || kind === null || kind === 'entry') return -1;
  if (typeof kind === 'string' && kind.indexOf('step-') === 0) {
    var n = parseInt(kind.slice(5), 10);
    return isNaN(n) ? -1 : n;
  }
  return -1;
}

function _ie_getCond(ed, secPath, idx, kind) {
  var si = _ie_kindStep(kind);
  if (!ed[secPath] || !ed[secPath][idx]) return null;
  if (si < 0) return ed[secPath][idx].condition || null;
  if (!ed[secPath][idx].steps || !ed[secPath][idx].steps[si]) return null;
  return ed[secPath][idx].steps[si].condition || null;
}

function _ie_setCond(ed, secPath, idx, kind, newCond) {
  var si = _ie_kindStep(kind);
  if (!ed[secPath]) ed[secPath] = [];
  if (!ed[secPath][idx]) ed[secPath][idx] = {};
  if (si < 0) {
    if (newCond) ed[secPath][idx].condition = newCond;
    else delete ed[secPath][idx].condition;
  } else {
    if (!ed[secPath][idx].steps) ed[secPath][idx].steps = [];
    if (!ed[secPath][idx].steps[si]) ed[secPath][idx].steps[si] = {};
    if (newCond) ed[secPath][idx].steps[si].condition = newCond;
    else delete ed[secPath][idx].steps[si].condition;
  }
}

function _ie_syncCond(ed, secId, secPath, idx, kind) {
  var card = document.querySelector('.obj-card[data-card="' + secId + '"]');
  if (!card) return;
  var si = _ie_kindStep(kind);
  var container;
  if (si < 0) {
    container = card.querySelector('.obj-sub-row.ie-inter-row[data-idx="' + idx + '"]');
  } else {
    container = card.querySelector('.obj-sub-row.ie-inter-row[data-idx="' + idx + '"] .ie-step-row[data-step="' + si + '"]');
  }
  if (!container) return;
  var condRoot = container.querySelector('.ie-cond-root');
  if (!condRoot) return;
  var cond = ie_collectCond(condRoot);
  _ie_setCond(ed, secPath, idx, kind, cond);
}

// ── Navigation in condition tree ──

function ie_condAt(cond, path) {
  if (!path) return cond;
  var parts = path.split('-').map(Number);
  var cur = cond;
  for (var i = 0; i < parts.length; i++) {
    if (!cur || (!cur.all_of && !cur.any_of)) return null;
    var children = cur.all_of || cur.any_of || [];
    if (parts[i] >= children.length) return null;
    cur = children[parts[i]];
  }
  return cur;
}

function ie_condReplace(cond, path, newVal) {
  if (!path) return newVal;
  if (!cond) return cond;
  var parts = path.split('-').map(Number);

  function replace(cur, depth) {
    if (depth === parts.length) return newVal;
    if (!cur || (!cur.all_of && !cur.any_of)) return cur;
    var mode = cur.all_of ? 'all_of' : 'any_of';
    var children = (cur.all_of || cur.any_of).slice();
    children[parts[depth]] = replace(children[parts[depth]], depth + 1);
    children = children.filter(function(c) { return c !== null; });
    if (children.length === 0) return null;
    var r = {};
    if (cur.not) r.not = true;
    r[mode] = children;
    return r;
  }

  return replace(cond, 0);
}

// ── Clean condition tree for save ──

function ie_cleanCondition(cond) {
  if (!cond || typeof cond !== 'object') return null;
  if (cond.all_of || cond.any_of) {
    var mode = cond.all_of ? 'all_of' : 'any_of';
    var cleaned = cond[mode].map(ie_cleanCondition).filter(function(c) { return c !== null; });
    if (cleaned.length === 0) return null;
    if (cleaned.length === 1 && !cond.not) return cleaned[0];
    var r = {};
    if (cond.not) r.not = true;
    r[mode] = cleaned;
    return r;
  }
  var not = !!cond.not;
  var leaf = null;
  if (cond.global_flag !== undefined) {
    if (cond.global_flag) {
      leaf = { global_flag: cond.global_flag };
      if (cond.value !== undefined) leaf.value = cond.value;
    }
  } else if (cond.player_flag !== undefined) {
    if (cond.player_flag) {
      leaf = { player_flag: cond.player_flag };
      if (cond.value !== undefined) leaf.value = cond.value;
    }
  } else if (cond.room !== undefined) {
    if (cond.room) leaf = { room: parseInt(cond.room, 10) || 0 };
  } else if (cond.has_item !== undefined) {
    if (cond.has_item) leaf = { has_item: cond.has_item };
  } else if (cond.min_credits !== undefined) {
    var mc = parseInt(cond.min_credits, 10);
    if (!isNaN(mc)) leaf = { min_credits: mc };
  }
  if (!leaf) return null;
  if (not) leaf.not = true;
  return leaf;
}

// ── Collect condition from DOM ──

function ie_collectCond(rootEl) {
  if (!rootEl) return null;

  if (rootEl.classList.contains('ie-cond-root')) {
    var groupEl = rootEl.querySelector(':scope > .ie-cond');
    if (groupEl) return ie_collectCond(groupEl);
    var leafEl = rootEl.querySelector(':scope > .ie-cond-leaf');
    if (leafEl) return ie_collectLeaf(leafEl);
    return null;
  }

  var mode = 'all_of';
  var modeSel = rootEl.querySelector(':scope > .ie-cond-modebar .ie-cond-modesel');
  if (modeSel) mode = modeSel.value;
  var notCb = rootEl.querySelector(':scope > .ie-cond-modebar .ie-cond-not');
  var not = notCb ? notCb.checked : false;

  var container = rootEl.querySelector(':scope > .ie-cond-children');
  var items = [];
  if (container) {
    Array.prototype.forEach.call(container.children, function(child) {
      if (child.classList.contains('ie-cond-leaf')) {
        var leaf = ie_collectLeaf(child);
        if (leaf) items.push(leaf);
      } else if (child.classList.contains('ie-cond')) {
        var sub = ie_collectCond(child);
        if (sub) items.push(sub);
      }
    });
  }

  var result = {};
  if (not) result.not = true;
  result[mode] = items;
  return result;
}

function ie_collectLeaf(el) {
  var leafType = el.getAttribute('data-ie-leaftype');
  if (!leafType) return null;
  var result = {};
  var notCb = el.querySelector('.ie-cond-not');
  if (notCb && notCb.checked) result.not = true;

  var valInput = el.querySelector('.ie-cond-val');
  var val = valInput ? valInput.value.trim() : '';

  switch (leafType) {
    case 'global_flag':
      result.global_flag = val;
      var gfSubInput = el.querySelector('.ie-cond-subval');
      if (gfSubInput && gfSubInput.value.trim()) {
        var gfsv = gfSubInput.value.trim();
        try { result.value = JSON.parse(gfsv); } catch(e) { result.value = gfsv; }
      }
      break;
    case 'player_flag':
      result.player_flag = val;
      var subInput = el.querySelector('.ie-cond-subval');
      if (subInput && subInput.value.trim()) {
        var sv = subInput.value.trim();
        try { result.value = JSON.parse(sv); } catch(e) { result.value = sv; }
      }
      break;
    case 'room':
      result.room = parseInt(val) || 0;
      break;
    case 'has_item':
      result.has_item = val;
      break;
    case 'min_credits':
      result.min_credits = parseInt(val) || 0;
      break;
    default:
      return null;
  }
  return result;
}

// ── Render condition ──

function ie_renderCond(condObj, secId, idx, secPath, kind, opts) {
  kind = kind || 'entry';
  opts = opts || {};
  var scopeAttr = opts.scopeToken ? ' data-ie-scope="' + escAttr(opts.scopeToken) + '"' : '';
  var h = '';
  var isGroup = condObj && (condObj.all_of || condObj.any_of);
  var rootChildCount = isGroup ? (condObj.all_of || condObj.any_of || []).length : 0;
  if (condObj && typeof condObj === 'object') {
    var condTitleText = '';
    if (kind && kind.indexOf('step-') === 0) {
      var sn = parseInt(kind.slice(5), 10);
      if (!isNaN(sn)) condTitleText = 'Condition for Step ' + (sn + 1);
    } else if (kind === 'entry' && !opts.scopeToken) {
      condTitleText = 'Condition for Action Block';
    }
    h += '<div class="ie-cond-root"' + scopeAttr + '>';
    if (condTitleText) h += '<div class="ie-cond-title">' + esc(condTitleText) + '</div>';
    h += ie_renderGroup(condObj, secId, secPath, idx, '', kind);
    h += '</div>';
  }
  var showAddbar = (!isGroup || (opts.alwaysOuterAddbar && rootChildCount === 0)) && typeof condObj === 'object';
  if (showAddbar) {
    h += '<div class="ie-cond-addbar"' + scopeAttr + '>';
    IE_COND_TYPES.forEach(function(ct) {
      h += '<button class="btn btn-sm ie-add-btn ie-cond-add-leaf" onclick="ie_addOuterLeaf(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + ct.type + '\')">+ ' + esc(ct.label) + '</button>';
    });
    h += '<button class="btn btn-sm ie-add-btn ie-cond-add-grp" onclick="ie_addOuterGroup(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\')">+ Group</button>';
    h += '</div>';
  }
  return h;
}

function ie_renderGroup(cond, secId, secPath, idx, gpath, kind) {
  var mode = null, children = null;
  if (cond.all_of) { mode = 'all_of'; children = cond.all_of; }
  else if (cond.any_of) { mode = 'any_of'; children = cond.any_of; }

  var not = !!cond.not;

  if (mode && children) {
    return _ie_renderGroupNode(mode, children, not, secId, secPath, idx, gpath, kind);
  }

  if (cond.global_flag !== undefined) return _ie_renderLeaf('global_flag', cond.global_flag, cond.value, not, secId, secPath, idx, gpath, IE_ROOT_LEAF, kind);
  if (cond.player_flag !== undefined) return _ie_renderLeaf('player_flag', cond.player_flag, cond.value, not, secId, secPath, idx, gpath, IE_ROOT_LEAF, kind);
  if (cond.room !== undefined) return _ie_renderLeaf('room', cond.room, '', not, secId, secPath, idx, gpath, IE_ROOT_LEAF, kind);
  if (cond.has_item !== undefined) return _ie_renderLeaf('has_item', cond.has_item, '', not, secId, secPath, idx, gpath, IE_ROOT_LEAF, kind);
  if (cond.min_credits !== undefined) return _ie_renderLeaf('min_credits', cond.min_credits, '', not, secId, secPath, idx, gpath, IE_ROOT_LEAF, kind);

  return '';
}

function _ie_renderGroupNode(mode, children, not, secId, secPath, idx, gpath, kind) {
  var h = '';

  if (children.length === 0) {
    h += '<div class="ie-cond ie-cond-empty" data-ie-gpath="' + escAttr(gpath) + '">';
    h += '<div class="ie-cond-modebar ie-cond-empty-bar">';
    h += '<div class="ie-cond-addbar">';
    IE_COND_TYPES.forEach(function(ct) {
      h += '<button class="btn btn-sm ie-add-btn ie-cond-add-leaf" onclick="ie_addLeaf(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\',\'' + ct.type + '\')">+ ' + esc(ct.label) + '</button>';
    });
    h += '<button class="btn btn-sm ie-add-btn ie-cond-add-grp" onclick="ie_addGroup(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\')">+ Group</button>';
    h += '</div>';
    h += '<button class="btn btn-sm btn-danger ie-cond-grp-rm" onclick="ie_removeGroup(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\')" title="Remove this group">X</button>';
    h += '</div>';
    h += '</div>';
    return h;
  }

  h += '<div class="ie-cond" data-ie-gpath="' + escAttr(gpath) + '">';
  h += '<div class="ie-cond-modebar">';
  if (children.length >= 2) {
    h += '<select class="ie-cond-modesel" onchange="ie_toggleCondMode(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\')">';
    h += '<option value="all_of"' + (mode === 'all_of' ? ' selected' : '') + '>All of</option>';
    h += '<option value="any_of"' + (mode === 'any_of' ? ' selected' : '') + '>Any of</option>';
    h += '</select>';
  }
  if (children.length >= 2 || not) {
    h += '<label class="ie-cond-notlbl"><input type="checkbox" class="ie-cond-not" onchange="ie_toggleCondNot(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\')"' + (not ? ' checked' : '') + '> NOT</label>';
  }
  h += '</div>';
  h += '<div class="ie-cond-children">';
  children.forEach(function(child, ci) {
    var cpath = gpath ? gpath + '-' + ci : String(ci);
    if (child.all_of || child.any_of) {
      h += ie_renderGroup(child, secId, secPath, idx, cpath, kind);
    } else {
      var cval = '', csub = '', ctype = '', cnot = !!child.not;
      if (child.global_flag !== undefined) { ctype = 'global_flag'; cval = child.global_flag; csub = child.value; }
      else if (child.player_flag !== undefined) { ctype = 'player_flag'; cval = child.player_flag; csub = child.value; }
      else if (child.room !== undefined) { ctype = 'room'; cval = child.room; }
      else if (child.has_item !== undefined) { ctype = 'has_item'; cval = child.has_item; }
      else if (child.min_credits !== undefined) { ctype = 'min_credits'; cval = child.min_credits; }
      if (ctype) h += _ie_renderLeaf(ctype, cval, csub, cnot, secId, secPath, idx, gpath, ci, kind);
    }
  });
  h += '</div>';
  h += '<div class="ie-cond-addbar" data-ie-gpath="' + escAttr(gpath) + '">';
  IE_COND_TYPES.forEach(function(ct) {
    h += '<button class="btn btn-sm ie-add-btn ie-cond-add-leaf" onclick="ie_addLeaf(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\',\'' + ct.type + '\')">+ ' + esc(ct.label) + '</button>';
  });
  h += '<button class="btn btn-sm ie-add-btn ie-cond-add-grp" onclick="ie_addGroup(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\')">+ Group</button>';
  h += '</div>';
  h += '</div>';
  return h;
}

function _ie_renderLeaf(leafType, leafVal, leafSub, not, secId, secPath, idx, gpath, ci, kind) {
  kind = kind || 'entry';
  var label = '';
  IE_COND_TYPES.forEach(function(ct) { if (ct.type === leafType) label = ct.label; });
  var hint = '';
  IE_COND_TYPES.forEach(function(ct) { if (ct.type === leafType) hint = ct.hint; });
  var isSearch = leafType === 'has_item';
  var sv = leafVal === undefined || leafVal === null ? '' : String(leafVal);
  var ssv = leafSub === undefined || leafSub === null ? '' : String(leafSub);
  var ciToken = (ci === undefined || ci === null) ? IE_ROOT_LEAF : ci;

  var h = '<div class="ie-cond-leaf" data-ie-leaftype="' + leafType + '">';
  h += '<span class="ie-cond-leaf-label">' + esc(label) + '</span>';
  if (isSearch) {
    h += '<div class="obj-search" style="position:relative;min-width:0;flex:1">';
    h += '<input class="ie-cond-val search-input" data-search-type="items" placeholder="' + escAttr(hint) + '" value="' + escAttr(sv) + '">';
    h += '<div class="search-results" style="display:none"></div>';
    h += '</div>';
  } else if (leafType === 'min_credits' || leafType === 'room') {
    h += '<input class="ie-cond-val" placeholder="' + escAttr(hint) + '" value="' + escAttr(sv) + '" type="number">';
  } else {
    h += '<input class="ie-cond-val" placeholder="' + escAttr(hint) + '" value="' + escAttr(sv) + '">';
  }
  if (leafType === 'player_flag' || leafType === 'global_flag') {
    h += '<span class="ie-cond-eq">=</span>';
    h += '<input class="ie-cond-subval" placeholder="exists" value="' + escAttr(ssv) + '">';
  }
  h += '<label class="ie-cond-notlbl"><input type="checkbox" class="ie-cond-not" onchange="ie_toggleNotLeaf(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\',' + ciToken + ')"' + (not ? ' checked' : '') + '> NOT</label>';
  h += '<button class="btn btn-sm btn-danger ie-cond-rm" onclick="ie_removeCond(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',\'' + escAttr(kind) + '\',\'' + escAttr(gpath) + '\',' + ciToken + ')" title="Remove">X</button>';
  h += '</div>';
  return h;
}

// ── Render step effects (everything except messages and condition).
//     The add-bar is rendered separately via ie_renderStepAddbar. ──

function ie_renderAct(stepObj, secId, idx, si, secPath) {
  var hasAny = false;
  var rows = '';

  IE_ACT_TYPES.forEach(function(at) {
    if (!stepObj || !Object.prototype.hasOwnProperty.call(stepObj, at.key)) return;
    var val = stepObj[at.key];
    if (at.kind === 'checkbox' && val !== true) return;
    hasAny = true;

    if (at.kind === 'kv') {
      var kvMap = (val && typeof val === 'object') ? val : {};
      var kvKeys = Object.keys(kvMap);
      var kvRmAttr = 'ie_removeKVRow(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(at.key) + '\')';
      rows += '<div class="ie-act-kv" data-ie-act-key="' + escAttr(at.key) + '">';
      rows += '<div class="ie-act-kv-header"><span>' + esc(at.label) + '</span></div>';
      rows += '<div class="ie-kv-list">';
      if (kvKeys.length === 0) {
        rows += '<div class="ie-kv-row"><input value="" placeholder="key" class="ie-kv-key">';
        rows += '<input value="" placeholder="val" class="ie-kv-val">';
        rows += '<button class="btn btn-sm btn-danger" onclick="' + kvRmAttr + '">X</button></div>';
      } else {
        kvKeys.forEach(function(k) {
          rows += '<div class="ie-kv-row"><input value="' + escAttr(k) + '" placeholder="key" class="ie-kv-key">';
          rows += '<input value="' + escAttr(kvMap[k] == null ? '' : String(kvMap[k])) + '" placeholder="val" class="ie-kv-val">';
          rows += '<button class="btn btn-sm btn-danger" onclick="' + kvRmAttr + '">X</button></div>';
        });
      }
      rows += '</div>';
      rows += '<button class="btn btn-sm ie-add-btn" style="margin-top:2px" onclick="ie_addKVRow(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(at.key) + '\')">+ Add</button>';
      rows += '</div>';
    } else if (at.kind === 'checkbox') {
      rows += '<div class="ie-act-row"><span class="ie-act-label">' + esc(at.label) + '</span>';
      rows += '<input type="checkbox" class="ie-act-input" data-ie-act-key="' + escAttr(at.key) + '" data-ie-act-kind="checkbox" checked hidden>';
      rows += '<button class="btn btn-sm btn-danger ie-act-rm" onclick="ie_removeActEffect(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(at.key) + '\')">X</button>';
      rows += '</div>';
    } else if (at.kind === 'search') {
      rows += '<div class="ie-act-row"><span class="ie-act-label">' + esc(at.label) + '</span>';
      rows += '<div class="obj-search" style="position:relative;min-width:0;flex:1"><input class="ie-act-input search-input" data-ie-act-key="' + escAttr(at.key) + '" data-search-type="' + escAttr(at.entity) + '" placeholder="' + escAttr(at.hint || 'Search ' + at.entity + '...') + '" value="' + escAttr(val == null ? '' : String(val)) + '"><div class="search-results" style="display:none"></div></div>';
      rows += '<button class="btn btn-sm btn-danger ie-act-rm" onclick="ie_removeActEffect(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(at.key) + '\')">X</button>';
      rows += '</div>';
    } else if (at.kind === 'droptable') {
      rows += '<div class="ie-act-kv" data-ie-act-key="drop_table">';
      rows += '<div class="ie-act-kv-header"><span>Drop Table</span><button class="btn btn-sm btn-danger ie-act-rm" style="margin-left:auto" onclick="ie_removeActEffect(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'drop_table\')">X</button></div>';
      rows += ie_renderDropTableBlock(val, 'ie_addDropRow(this,\''+escAttr(secId)+'\',\''+escAttr(secPath)+'\','+idx+','+si+',\'item\')', 'ie_addDropRow(this,\''+escAttr(secId)+'\',\''+escAttr(secPath)+'\','+idx+','+si+',\'table\')', 'ie_removeDropRow(this,\''+escAttr(secId)+'\',\''+escAttr(secPath)+'\','+idx+','+si+',__RI__)');
      rows += '<div class="obj-drop-view"></div>';
      rows += '</div>';
    } else {
      rows += '<div class="ie-act-row"><span class="ie-act-label">' + esc(at.label) + '</span>';
      rows += '<input class="ie-act-input" data-ie-act-key="' + escAttr(at.key) + '"' + (at.kind === 'number' ? ' type="number"' : '') + ' data-ie-act-kind="' + escAttr(at.kind) + '" value="' + escAttr(val == null ? '' : String(val)) + '" placeholder="' + escAttr(at.hint || '') + '" style="flex:1">';
      rows += '<button class="btn btn-sm btn-danger ie-act-rm" onclick="ie_removeActEffect(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(at.key) + '\')">X</button>';
      rows += '</div>';
      if (at.kind === 'text') {
        rows += ced_renderTagHelp('trigger');
      }
    }
  });

  if (hasAny) {
    return '<div class="ie-act-root">' + rows + '</div>';
  }
  return '';
}

// ── Render messages sub-list (plain strings) ──

function ie_renderMessages(step, secId, idx, si, secPath) {
  var present = step && Array.isArray(step.messages);
  if (!present) {
    return '';
  }
  var msgs = step.messages;
  var rmFn = 'ie_removeMessage(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ')';
  var h = '<div class="ie-act-kv" data-ie-act-key="messages">';
  h += '<div class="ie-act-kv-header"><span>Messages</span></div>';
  h += '<div class="ie-kv-list">';
  msgs.forEach(function(m, mi) {
    var upBtn = mi > 0
      ? '<button class="btn btn-sm ie-msg-up" onclick="ie_moveMessage(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',' + mi + ',' + (mi - 1) + ')" title="Move up">&#9650;</button>'
      : '';
    var dnBtn = mi < msgs.length - 1
      ? '<button class="btn btn-sm ie-msg-dn" onclick="ie_moveMessage(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',' + mi + ',' + (mi + 1) + ')" title="Move down">&#9660;</button>'
      : '';
    h += '<div class="ie-kv-row ie-msg-row"><input class="ie-act-msg" data-ie-msg-idx="' + mi + '" value="' + escAttr(String(m)) + '" placeholder="Shown to player" style="flex:1">' + upBtn + dnBtn + '<button class="btn btn-sm btn-danger" onclick="' + rmFn + '">X</button></div>';
  });
  h += '</div>';
  h += '<button class="btn btn-sm ie-add-btn" style="margin-top:2px" onclick="ie_addMessage(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ')">+ Add Message</button>';
  h += ced_renderTagHelp('trigger');
  h += '</div>';
  return h;
}

// ── Render steps list of a trigger entry ──

function ie_renderStepList(steps, secId, idx, secPath) {
  steps = steps || [];
  var h = '<div class="ie-step-list" data-idx="' + idx + '">';
  steps.forEach(function(step, si) {
    var stepCond = step && step.condition && typeof step.condition === 'object';
    h += '<div class="ie-step-row" data-step="' + si + '" data-idx="' + idx + '">';
    h += '<div class="ie-step-header">';
    h += '<span class="ie-step-label">Step ' + (si + 1) + '</span>';
    h += '<button class="btn btn-sm ie-step-addmore" onclick="this.closest(\'.ie-step-row\').classList.toggle(\'show-addbar\')" title="Add action to this step"></button>';
    if (!stepCond) {
      h += '<button class="btn btn-sm ie-add-btn" onclick="ie_addStepCond(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ')">+ Add Step Condition</button>';
    }
    h += '<span class="ie-step-spacer"></span>';
    if (si > 0) h += '<button class="btn btn-sm ie-step-up" onclick="ie_moveStep(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',' + (si - 1) + ')" title="Move up">&#9650;</button>';
    if (si < steps.length - 1) h += '<button class="btn btn-sm ie-step-dn" onclick="ie_moveStep(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',' + (si + 1) + ')" title="Move down">&#9660;</button>';
    h += '<button class="btn btn-sm btn-danger" onclick="ie_removeStep(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ')" title="Remove step">X</button>';
    h += '</div>';

    if (stepCond) {
      h += '<div class="ie-step-cond-panel">';
      h += ie_renderCond(step.condition || null, secId, idx, secPath, 'step-' + si);
      h += '</div>';
    }

    h += '<div class="ie-step-effects">' + ie_renderAct(step, secId, idx, si, secPath) + '</div>';
    h += '<div class="ie-step-messages">' + ie_renderMessages(step, secId, idx, si, secPath) + '</div>';
    h += '<div class="ie-step-addbar">' + ie_renderStepAddbar(step, secId, idx, si, secPath) + '</div>';

    h += '</div>';
  });
  h += '<div class="ie-step-addbar-bottom">' + ie_renderBottomAddbar(secId, secPath, idx) + '</div>';
  h += '</div>';
  return h;
}

// ── Collect effects (everything except messages and condition) ──

function ie_collectAct(container) {
  if (!container) return null;
  var r = {};

  container.querySelectorAll('.ie-act-kv').forEach(function(kvEl) {
    var key = kvEl.getAttribute('data-ie-act-key');
    if (!key) return;
    if (key === 'messages') return;
    if (key === 'drop_table') {
      var dt = ie_collectDropTableBlock(kvEl.querySelector('.ie-drop-table'));
      if (dt) r.drop_table = dt;
      return;
    }
    var map = {};
    kvEl.querySelectorAll('.ie-kv-row').forEach(function(row) {
      var kEl = row.querySelector('.ie-kv-key');
      var vEl = row.querySelector('.ie-kv-val');
      if (kEl && kEl.value.trim() && vEl) {
        var v = vEl.value.trim();
        var num = parseFloat(v);
        map[kEl.value.trim()] = v === 'true' ? true : (v === 'false' ? false : (!isNaN(num) ? num : v));
      }
    });
    r[key] = map;
  });

  container.querySelectorAll('.ie-act-input').forEach(function(el) {
    var key = el.getAttribute('data-ie-act-key');
    if (!key) return;
    var kind = el.getAttribute('data-ie-act-kind');
    if (kind === 'checkbox') {
      r[key] = el.checked;
    } else if (kind === 'number') {
      var n = parseFloat(el.value);
      if (isNaN(n)) return;
      r[key] = n;
    } else {
      r[key] = el.value.trim();
    }
  });

  if (Object.keys(r).length === 0) return null;
  return r;
}

// ── Collect messages (plain strings) ──

function ie_collectMessages(container) {
  if (!container) return null;
  var msgsKv = container.querySelector('.ie-act-kv[data-ie-act-key="messages"]');
  if (!msgsKv) return null;
  var list = [];
  msgsKv.querySelectorAll('.ie-kv-row .ie-act-msg').forEach(function(el) {
    list.push(el.value.trim());
  });
  return list;
}

// ── Sync a single step's DOM back into data ──

function ie_syncStep(ed, secId, secPath, idx, si) {
  var card = document.querySelector('.obj-card[data-card="' + secId + '"]');
  if (!card) return;
  var stepRow = card.querySelector('.obj-sub-row.ie-inter-row[data-idx="' + idx + '"] .ie-step-row[data-step="' + si + '"]');
  if (!stepRow) return;
  if (!ed[secPath] || !ed[secPath][idx] || !ed[secPath][idx].steps || !ed[secPath][idx].steps[si]) return;
  var step = ed[secPath][idx].steps[si];

  var condRoot = stepRow.querySelector(':scope > .ie-step-cond-panel .ie-cond-root');
  if (condRoot) {
    var cond = ie_collectCond(condRoot);
    if (cond) step.condition = cond; else delete step.condition;
  }

  var effContainer = stepRow.querySelector(':scope > .ie-step-effects');
  if (effContainer) {
    var act = ie_collectAct(effContainer);
    if (act) {
      Object.keys(act).forEach(function(k) { step[k] = act[k]; });
    }
    // Drop keys the user X'd out (no longer present in the DOM among the rendered IE_ACT_TYPES set).
    IE_ACT_TYPES.forEach(function(at) {
      if (at.key === 'messages') return;
      if (!Object.prototype.hasOwnProperty.call(act || {}, at.key)) {
        if (Object.prototype.hasOwnProperty.call(step, at.key)) delete step[at.key];
      }
    });
  }

  var msgsContainer = stepRow.querySelector(':scope > .ie-step-messages');
  if (msgsContainer) {
    var list = ie_collectMessages(msgsContainer);
    if (list !== null) step.messages = list;
    else delete step.messages;
    if (Array.isArray(step.messages) && step.messages.length === 0) {
      // keep empty array — survives next render, ced_cleanOutput will strip
      // it on save.
    }
  }
}

// ── Sync all interaction DOM back to data ──

function ie_syncAllInteractions(data, secs) {
  if (!data || !secs) return;
  secs.forEach(function(sec) {
    if (!sec.interactionStyle || !sec.isArray) return;
    var p = sec.path;
    if (!data[p]) return;
    var card = document.querySelector('.obj-card[data-card="' + sec.id + '"]');
    if (!card) return;
    var rows = card.querySelectorAll('.obj-sub-row.ie-inter-row');
    rows.forEach(function(row, idx) {
      if (!data[p][idx]) data[p][idx] = {};
      var lockCb = row.querySelector(':scope > .ie-inter-header .ie-lock-cb');
      if (lockCb) {
        if (lockCb.checked) data[p][idx].lock = true;
        else delete data[p][idx].lock;
      }
      var entryCondRoot = row.querySelector(':scope > .ie-inter-panel .ie-cond-root');
      if (entryCondRoot) {
        var cond = ie_collectCond(entryCondRoot);
        if (cond) data[p][idx].condition = cond;
        else delete data[p][idx].condition;
      }
      if (!data[p][idx].steps) data[p][idx].steps = [];
      var stepRows = row.querySelectorAll(':scope > .ie-inter-steps .ie-step-row');
      stepRows.forEach(function(stepRow) {
        var si = parseInt(stepRow.getAttribute('data-step'), 10);
        if (isNaN(si)) return;
        ie_syncStep(data, sec.id, p, idx, si);
      });
    });
  });
}

// ── Add/Remove/Toggle: Condition ──

function ie_addLeaf(el, secId, secPath, idx, kind, groupPath, leafType) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  var cond = c.get();
  var leaf = {};
  leaf[leafType] = (leafType === 'min_credits' || leafType === 'room') ? 0 : '';
  var group = ie_condAt(cond, groupPath);
  var newGroup;
  if (!group) {
    newGroup = leaf;
  } else if (group.all_of || group.any_of) {
    var mode = group.all_of ? 'all_of' : 'any_of';
    var children = (group.all_of || group.any_of).concat([leaf]);
    newGroup = {};
    if (group.not) newGroup.not = true;
    newGroup[mode] = children;
  } else {
    newGroup = {all_of: [group, leaf]};
  }
  cond = ie_condReplace(cond, groupPath, newGroup);
  c.set(cond);
  c.change();
}

function ie_removeCond(el, secId, secPath, idx, kind, groupPath, childIdx) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  var cond = c.get();
  if (childIdx === IE_ROOT_LEAF) {
    c.set(null);
    c.change();
    return;
  }
  var group = ie_condAt(cond, groupPath);
  if (!group) return;
  if (group.all_of || group.any_of) {
    var mode = group.all_of ? 'all_of' : 'any_of';
    var children = (group.all_of || group.any_of).slice();
    children.splice(childIdx, 1);
    var newGroup;
    if (children.length === 0) {
      newGroup = null;
    } else if (children.length === 1 && !group.not) {
      newGroup = children[0];
    } else {
      newGroup = {};
      if (group.not) newGroup.not = true;
      newGroup[mode] = children;
    }
    cond = ie_condReplace(cond, groupPath, newGroup);
  } else {
    cond = ie_condReplace(cond, groupPath, null);
  }
  c.set(cond);
  c.change();
}

function ie_removeGroup(el, secId, secPath, idx, kind, groupPath) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  var cond = c.get();
  if (!groupPath) {
    c.set(null);
    c.change();
    return;
  }
  var parts = groupPath.split('-').map(Number);
  var childIdx = parts[parts.length - 1];
  var parentPath = parts.slice(0, -1).join('-');
  var parent = ie_condAt(cond, parentPath);
  if (!parent || !(parent.all_of || parent.any_of)) return;
  var mode = parent.all_of ? 'all_of' : 'any_of';
  var children = parent[mode].slice();
  children.splice(childIdx, 1);
  var newParent;
  if (children.length === 0) {
    newParent = null;
  } else if (children.length === 1 && !parent.not) {
    newParent = children[0];
  } else {
    newParent = {};
    if (parent.not) newParent.not = true;
    newParent[mode] = children;
  }
  cond = ie_condReplace(cond, parentPath, newParent);
  c.set(cond);
  c.change();
}

function ie_addRootConditionGroup(secPath, idx, kind) {
  var ed = window._editorData;
  if (!ed) return;
  if (!ed[secPath]) ed[secPath] = [];
  if (!ed[secPath][idx]) ed[secPath][idx] = {};
  var si = _ie_kindStep(kind);
  if (si < 0) {
    if (!ed[secPath][idx].condition || typeof ed[secPath][idx].condition !== 'object') {
      ed[secPath][idx].condition = {all_of: []};
    }
  } else {
    if (!ed[secPath][idx].steps) ed[secPath][idx].steps = [];
    if (!ed[secPath][idx].steps[si]) ed[secPath][idx].steps[si] = {};
    if (!ed[secPath][idx].steps[si].condition || typeof ed[secPath][idx].steps[si].condition !== 'object') {
      ed[secPath][idx].steps[si].condition = {all_of: []};
    }
  }
  ced_syncDOMToData(ed);
  window._ieRenderOnly();
}

function ie_addStepCond(el, secId, secPath, idx, si) {
  if (el && el.nodeType && _ie_scopeFromEl(el)) {
    var c = _ie_condCtx(el, secId, secPath, idx, 'step-' + si);
    c.get();
    c.change();
    return;
  }
  ie_addRootConditionGroup(secPath, idx, 'step-' + si);
}

function ie_addGroup(el, secId, secPath, idx, kind, groupPath) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  var cond = c.get();
  var group = ie_condAt(cond, groupPath);
  var newSub = {all_of: []};
  var newGroup;
  if (!group) {
    newGroup = newSub;
  } else if (group.all_of || group.any_of) {
    var mode = group.all_of ? 'all_of' : 'any_of';
    var children = (group.all_of || group.any_of).concat([newSub]);
    newGroup = {};
    if (group.not) newGroup.not = true;
    newGroup[mode] = children;
  } else {
    newGroup = {all_of: [group, newSub]};
  }
  cond = ie_condReplace(cond, groupPath, newGroup);
  c.set(cond);
  c.change();
}

function ie_addOuterLeaf(el, secId, secPath, idx, kind, leafType) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  var cond = c.get();
  var leaf = {};
  leaf[leafType] = (leafType === 'min_credits' || leafType === 'room') ? 0 : '';
  if (!cond) {
    cond = leaf;
  } else {
    cond = {all_of: [cond, leaf]};
  }
  c.set(cond);
  c.change();
}

function ie_addOuterGroup(el, secId, secPath, idx, kind) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  var cond = c.get();
  var newSub = {all_of: []};
  if (!cond) {
    cond = newSub;
  } else {
    cond = {all_of: [cond, newSub]};
  }
  c.set(cond);
  c.change();
}

function ie_toggleCondMode(el, secId, secPath, idx, kind, groupPath) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  c.get();
  c.change();
}

function ie_toggleCondNot(el, secId, secPath, idx, kind, groupPath) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  c.get();
  c.change();
}

function ie_toggleNotLeaf(el, secId, secPath, idx, kind, groupPath, ci) {
  var c = _ie_condCtx(el, secId, secPath, idx, kind);
  c.get();
  c.change();
}

// ── Add/Remove: Steps ──

function ie_removeStep(el, secId, secPath, idx, si) {
  var ed = window._editorData;
  if (!ed) return;
  ced_syncDOMToData(ed);
  if (window._ieSyncAll) window._ieSyncAll(ed);
  if (!ed[secPath] || !ed[secPath][idx] || !ed[secPath][idx].steps) return;
  ed[secPath][idx].steps.splice(si, 1);
  window._ieRenderCurrent();
}

function ie_moveStep(el, secId, secPath, idx, fromSi, toSi) {
  var ed = window._editorData;
  if (!ed) return;
  ced_syncDOMToData(ed);
  if (window._ieSyncAll) window._ieSyncAll(ed);
  var steps = ed[secPath] && ed[secPath][idx] && ed[secPath][idx].steps;
  if (!steps || fromSi < 0 || fromSi >= steps.length || toSi < 0 || toSi >= steps.length) return;
  var m = steps.splice(fromSi, 1)[0];
  steps.splice(toSi, 0, m);
  window._ieRenderOnly();
}

function ie_moveRow(secPath, fromIdx, toIdx) {
  var ed = window._editorData;
  if (!ed) return;
  ced_syncDOMToData(ed);
  if (window._ieSyncAll) window._ieSyncAll(ed);
  var arr = ed[secPath];
  if (!arr || fromIdx < 0 || fromIdx >= arr.length || toIdx < 0 || toIdx >= arr.length) return;
  var m = arr.splice(fromIdx, 1)[0];
  arr.splice(toIdx, 0, m);
  window._ieRenderOnly();
}

function ie_moveMessage(el, secId, secPath, idx, si, fromMi, toMi) {
  var c = _ie_actCtx(el, secId, secPath, idx, si);
  var step = c.get();
  if (!step || !Array.isArray(step.messages)) return;
  if (fromMi < 0 || fromMi >= step.messages.length || toMi < 0 || toMi >= step.messages.length) return;
  var m = step.messages.splice(fromMi, 1)[0];
  step.messages.splice(toMi, 0, m);
  c.set(step);
  c.change();
}

// ── Add/Remove: Action effects ──

function ie_addActEffect(el, secId, secPath, idx, si, effectKey) {
  var c = _ie_actCtx(el, secId, secPath, idx, si);
  var step = c.get();
  var at = IE_ACT_TYPES.find(function(a) { return a.key === effectKey; });
  if (!at) return;
  if (at.kind === 'kv') step[effectKey] = {};
  else if (at.kind === 'checkbox') step[effectKey] = true;
  else if (at.kind === 'number') step[effectKey] = 0;
  else if (at.kind === 'droptable') step[effectKey] = [];
  else step[effectKey] = '';
  c.set(step);
  c.change();
}

function ie_removeActEffect(el, secId, secPath, idx, si, effectKey) {
  var c = _ie_actCtx(el, secId, secPath, idx, si);
  var step = c.get();
  delete step[effectKey];
  c.set(step);
  c.change();
}

// ── Add/Remove: KV row ──

function ie_addKVRow(el, secId, secPath, idx, si, effectKey) {
  if (_ie_scopeFromEl(el)) {
    var c = _ie_actCtx(el, secId, secPath, idx, si);
    var step = c.get();
    if (!step[effectKey] || typeof step[effectKey] !== 'object') step[effectKey] = {};
    step[effectKey][''] = '';
    c.set(step);
    c.change();
    return;
  }

  var ed = window._editorData;
  if (!ed) return;
  ie_syncStep(ed, secId, secPath, idx, si);
  var card = document.querySelector('.obj-card[data-card="' + secId + '"]');
  if (!card) return;
  var stepRow = card.querySelector('.obj-sub-row.ie-inter-row[data-idx="' + idx + '"] .ie-step-row[data-step="' + si + '"]');
  if (!stepRow) return;
  var list = stepRow.querySelector('.ie-act-kv[data-ie-act-key="' + effectKey + '"] .ie-kv-list');
  if (!list) return;
  var rowEl = document.createElement('div');
  rowEl.className = 'ie-kv-row';
  rowEl.innerHTML = '<input value="" placeholder="key" class="ie-kv-key"><input value="" placeholder="val" class="ie-kv-val"><button class="btn btn-sm btn-danger" onclick="ie_removeKVRow(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ',\'' + escAttr(effectKey) + '\')">X</button>';
  list.appendChild(rowEl);
  rowEl.querySelector('.ie-kv-key').focus();
}

function ie_removeKVRow(rowEl, secId, secPath, idx, si, effectKey) {
  if (rowEl && rowEl.closest) {
    var kvRow = rowEl.closest('.ie-kv-row');
    if (kvRow) rowEl = kvRow;
  }
  var c = _ie_actCtx(rowEl, secId, secPath, idx, si);
  var step = c.get();
  if (!step || !step.hasOwnProperty(effectKey)) return;
  var keyEl = rowEl.querySelector('.ie-kv-key');
  var k = keyEl ? keyEl.value.trim() : '';
  if (k && step[effectKey].hasOwnProperty(k)) delete step[effectKey][k];
  if (Object.keys(step[effectKey]).length === 0) delete step[effectKey];
  c.set(step);
  c.change();
}

// ── Add/Remove: Messages ──

function ie_addMessages(el, secId, secPath, idx, si) {
  var c = _ie_actCtx(el, secId, secPath, idx, si);
  var step = c.get();
  if (!step.messages || !Array.isArray(step.messages)) step.messages = [];
  step.messages.push('');
  c.set(step);
  c.change();
}

// ── Drop Table row add/remove ──

function ie_addDropRow(el, secId, secPath, idx, si, kind) {
  var c = _ie_actCtx(el, secId, secPath, idx, si);
  var step = c.get();
  if (!Array.isArray(step.drop_table)) step.drop_table = [];
  if (kind === 'table') {
    step.drop_table.push({table: '', weight: 10, quantity: 1, _kind: 'table'});
  } else {
    step.drop_table.push({item_id: '', weight: 10, quantity: 1, _kind: 'item'});
  }
  c.set(step);
  c.change();
}

function ie_removeDropRow(el, secId, secPath, idx, si, ri) {
  var c = _ie_actCtx(el, secId, secPath, idx, si);
  var step = c.get();
  if (!Array.isArray(step.drop_table)) return;
  step.drop_table.splice(ri, 1);
  c.set(step);
  c.change();
}

function ie_addMessage(el, secId, secPath, idx, si) {
  if (_ie_scopeFromEl(el)) {
    var c = _ie_actCtx(el, secId, secPath, idx, si);
    var step = c.get();
    if (!step.messages || !Array.isArray(step.messages)) step.messages = [];
    step.messages.push('');
    c.set(step);
    c.change();
    return;
  }

  var ed = window._editorData;
  if (!ed) return;
  ie_syncStep(ed, secId, secPath, idx, si);
  var card = document.querySelector('.obj-card[data-card="' + secId + '"]');
  if (!card) return;
  var stepRow = card.querySelector('.obj-sub-row.ie-inter-row[data-idx="' + idx + '"] .ie-step-row[data-step="' + si + '"]');
  if (!stepRow) return;
  var list = stepRow.querySelector('.ie-act-kv[data-ie-act-key="messages"] .ie-kv-list');
  if (!list) return;
  var rowEl = document.createElement('div');
  rowEl.className = 'ie-kv-row ie-msg-row';
  var rmFn = 'ie_removeMessage(this,\'' + escAttr(secId) + '\',\'' + escAttr(secPath) + '\',' + idx + ',' + si + ')';
  rowEl.innerHTML = '<input class="ie-act-msg" value="" placeholder="Shown to player" style="flex:1"><button class="btn btn-sm btn-danger" onclick="' + rmFn + '">X</button>';
  list.appendChild(rowEl);
  rowEl.querySelector('.ie-act-msg').focus();
}

function ie_removeMessage(rowEl, secId, secPath, idx, si) {
  if (rowEl && rowEl.closest) {
    var kvRow = rowEl.closest('.ie-kv-row');
    if (kvRow) rowEl = kvRow;
  }
  var c = _ie_actCtx(rowEl, secId, secPath, idx, si);
  var step = c.get();
  if (!step || !Array.isArray(step.messages)) return;
  var kvRows = document.querySelectorAll('.ie-act-kv[data-ie-act-key="messages"] .ie-kv-row');
  for (var ri = 0; ri < kvRows.length; ri++) {
    if (kvRows[ri] === rowEl || kvRows[ri].contains(rowEl)) {
      step.messages.splice(ri, 1);
      break;
    }
  }
  if (step.messages.length === 0) delete step.messages;
  c.set(step);
  c.change();
}

// ── Shared trigger-style array-section renderer ──

function ie_renderArraySection(ctx) {
  var sec = ctx.sec;
  var data = ctx.data;
  var visMap = ctx.visMap;
  var arr = data[sec.path] || [];
  var h = '';
  var allowItem = sec.itemIDAllowed !== false;

  arr.forEach(function(item, idx) {
    visMap[idx] = visMap[idx] || {};
    var vis = visMap[idx];
    var showItem = allowItem && (vis.item_id || (item.item_id && item.item_id !== ''));
    var condExists = !!(item.condition && typeof item.condition === 'object');
    var lockVal = !!item.lock;
    var steps = item.steps || [];

    h += '<div class="obj-sub-row ie-inter-row" data-idx="' + idx + '">';
    h += '<div class="ie-inter-header">';
    h += '<label class="ie-lock-lbl"><input type="checkbox" class="ie-lock-cb"' + (lockVal ? ' checked' : '') + '> Lock Player</label>';
    if (idx > 0) h += '<button class="btn btn-sm ie-trig-up" onclick="ie_moveRow(\'' + escAttr(sec.path) + '\',' + idx + ',' + (idx - 1) + ')" title="Move up">&#9650;</button>';
    if (idx < arr.length - 1) h += '<button class="btn btn-sm ie-trig-dn" onclick="ie_moveRow(\'' + escAttr(sec.path) + '\',' + idx + ',' + (idx + 1) + ')" title="Move down">&#9660;</button>';

    if (allowItem) {
      if (!showItem) {
        h += '<button class="btn btn-sm ie-add-btn" onclick="' + ctx.showField(sec.id, idx, 'item_id') + '">+ Add Required Item</button>';
      } else {
        h += ctx.renderField(sec, sec.fields[0], data, idx, 'flex:1;min-width:0');
        h += '<button class="btn btn-sm btn-danger ie-inter-field-x" onclick="' + ctx.hideField(sec.id, idx, 'item_id') + '" title="Remove required item">X</button>';
      }
    }
    if (!condExists) {
      h += '<button class="btn btn-sm ie-add-btn" onclick="ie_addRootConditionGroup(\'' + escAttr(sec.path) + '\',' + idx + ',\'entry\')">+ Add Condition</button>';
    }
    h += '<span class="ie-inter-header-spacer"></span>';
    h += '<button class="btn btn-sm btn-danger ie-inter-remove" onclick="' + ctx.showRemove(idx) + '">Remove</button>';
    h += '</div>';

    h += '<div class="ie-inter-panel" style="display:' + (condExists ? 'block' : 'none') + '">';
    h += '<div class="ie-inter-panel-body">' + ie_renderCond(item.condition || null, sec.id, idx, sec.path, 'entry') + '</div>';
    h += '</div>';

    h += '<div class="ie-inter-steps">';
    h += ie_renderStepList(steps, sec.id, idx, sec.path);
    h += '</div>';

    h += '</div>';
  });

  h += '<button class="btn btn-sm obj-sub-add" onclick="' + ctx.onAdd() + '">+ Add ' + esc(sec.label || 'Trigger') + '</button>';
  return h;
}

// ── Show/Hide field on a row ──

function ie_showField(visMap, secId, idx, key) {
  if (!visMap[secId]) visMap[secId] = {};
  if (!visMap[secId][idx]) visMap[secId][idx] = {};
  visMap[secId][idx][key] = true;
}

function ie_hideField(visMap, secId, idx, key) {
  if (!visMap[secId]) visMap[secId] = {};
  if (!visMap[secId][idx]) visMap[secId][idx] = {};
  visMap[secId][idx][key] = false;
}

// ── Step-cleaning helper used by save paths ──

function ie_cleanStep(step) {
  var s = {};
  if (step && step.condition) {
    var c = ie_cleanCondition(step.condition);
    if (c) s.condition = c;
  }
  if (step && step.wait !== undefined && step.wait !== null && step.wait !== 0) s.wait = step.wait;
  if (step && Array.isArray(step.messages) && step.messages.filter(function(m){return m;}).length > 0) {
    s.messages = step.messages.filter(function(m){return m;});
  }
  IE_ACT_TYPES.forEach(function(at) {
    if (at.key === 'wait' || at.key === 'messages') return;
    if (!step || !Object.prototype.hasOwnProperty.call(step, at.key)) return;
    var v = step[at.key];
    if (v === undefined || v === null || v === '') return;
    if (at.key === 'drop_table' && Array.isArray(v)) {
      var cleaned = v.map(function(e) {
        var c = {};
        if (e.item_id) c.item_id = e.item_id;
        if (e.table) c.table = e.table;
        if (e.weight) c.weight = e.weight;
        if (e.quantity) c.quantity = e.quantity;
        return c;
      }).filter(function(e) { return Object.keys(e).length > 0; });
      if (cleaned.length > 0) s.drop_table = cleaned;
      return;
    }
    if (typeof v === 'object') {
      if (Object.keys(v).length === 0) return;
      s[at.key] = v;
    } else if (typeof v === 'boolean') {
      if (!v) return;
      s[at.key] = v;
    } else {
      s[at.key] = v;
    }
  });
  return s;
}

// ── Bindings (set by each editor) ──

window._ieRenderCurrent = function() {};
window._ieRenderOnly = function() {};