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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------------------------
// sheet/RulesDialog.tsx β€” W51-T18, the conditional formatting editor and the validation list
// editor (contract C2, contract C8, rulings R1 and R8).
//
// ⭐⭐ TWO DIALOGS IN ONE FILE, AND THAT IS A FENCE DECISION SAID OUT LOUD. This ticket's `files`
// list names `RulesDialog.tsx` and no second component file, and the validation editor is the
// same shape as the rules editor wearing one control instead of a list: a base-kit dialog with a
// body, a refusal line and one commit door. Putting it here keeps `SheetGrid.tsx` from growing a
// third inline panel; the alternative was widening the ticket's own fence, which a worker may not
// do. `ValidationDialog` is exported beside `RulesDialog` and neither knows about the other.
//
// β›”β›” CONTRACT C8, IN FULL. Both use `ui/ConfirmDialog::ConfirmDialog` as their SHELL: centred at
// min(420px, 100vw - 32px), Cancel first and focused, Tab trapped, Escape and backdrop cancel,
// focus returned to the opener. Nothing here writes a second Escape listener; `ConfirmDialog`
// reaches the ONE arbiter through `useOverlayLayer`, and a `document.addEventListener` added in
// this file would race it and win or lose on registration order.
//
// ⚠ THE SHELL GENUINELY CARRIES A LIST EDITOR, so no second dialog shape was built. Its `body` is
// a `ReactNode` and its panel scrolls, which is what a hundred rules need.
//
// ⭐⭐ S67-T12 (instruction 9, journey J9): EXCEL'S RULES MANAGER, LIST THEN DETAIL. Every rule
// used to be a fully expanded card, so fifty stored rules were fifty forms with no separation and
// a refusal computed from the whole list on open. Now each rule is ONE summary row (what it tests,
// its format preview, where it applies), clicking a row opens that rule's editor under it and
// closes any other, and a refusal is raised only by Save and only on the row it belongs to. The
// wider panel is `.lp-dialog:has(.sheet-rules)` in sheet-engine.css, the `:has()` precedent of
// `wave59/templates.css`, so the kit's own markup is untouched.
//
// ⚠ DESIGN CONTRACT: sentence case, no ALL CAPS chrome, scale tokens only and no literal
// font-size, colour tokens never hues, inline SVG on `currentColor` and no emoji, 150 ms ease-out
// on opacity and transform, and no em dash or en dash in any string that reaches a screen.
// ---------------------------------------------------------------------------------------------

import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { useCellRefHighlight } from "./refHighlight";
import {
  DEFAULT_BAR_FILL, DEFAULT_RULE_SCALE,
  RULE_FILLS, RULE_INKS, RULE_KIND_LABEL, RULE_OPS, RULE_OP_LABEL, RULE_SCALES,
  RULE_SCALE_MAX_TYPES, RULE_SCALE_MIN_TYPES, RULE_SCALE_TYPE_LABEL,
  addRule, blankRule, moveRule, rampBackground, rangeText, removeRule, ruleArity, ruleCondition,
  ruleKind, rulePaint, ruleRefusal, ruleSummary, scaleBackground, scaleEnds, updateRule,
} from "./rules";
import { listText, parseList } from "./validation";
import { CELL_COLOUR_PATTERN, MAX_SHEET_RULES, MAX_VALIDATION_LIST, SHEET_RULE_KINDS } from "./types";
import type { SheetRule, SheetRuleKind, SheetRuleOp, SheetRuleScaleType } from "./types";

export interface RulesDialogProps {
  open: boolean;
  /** The rules the tab carries today. The dialog edits a DRAFT and commits it once. */
  rules: readonly SheetRule[];
  /** The selection's range, which is what a new rule opens with. `A1` when nothing is selected. */
  range: string;
  onCancel: () => void;
  onSave: (rules: SheetRule[]) => void;
}

/**
 * ⚠ THE HOOKS LIVE BELOW THE `open` GATE, exactly as `ConfirmDialog` splits its own. The draft
 * has to START from the tab's rules every time the dialog opens, and a component that stays
 * mounted while closed would keep yesterday's draft and silently offer it back.
 */
export function RulesDialog({ open, rules, range, onCancel, onSave }: RulesDialogProps) {
  if (!open) return null;
  return <RulesSurface rules={rules} range={range} onCancel={onCancel} onSave={onSave} />;
}

/** The chevron a move button wears. Inline SVG on `currentColor`, never a glyph and never an
 *  emoji (DESIGN.md 4). One shape, rotated by CSS, so the pair cannot drift apart. */
function IconChevron() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" className="sheet-rules-icon">
      <path d="M4 10l4-4 4 4" fill="none" stroke="currentColor" strokeWidth="1.6"
            strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/** The cross a delete button wears. Same vocabulary as the shortcuts panel's close. */
function IconRemove() {
  return (
    <svg viewBox="0 0 16 16" aria-hidden="true" focusable="false" className="sheet-rules-icon">
      <path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" strokeWidth="1.6"
            strokeLinecap="round" />
    </svg>
  );
}

function RulesSurface({
  rules, range, onCancel, onSave,
}: Omit<RulesDialogProps, "open">) {
  const [draft, setDraft] = useState<SheetRule[]>(() => (rules ?? []).map((r) => ({ ...r })));
  /** ⭐ S67-T12: ONE rule is edited at a time, as in Excel's Rules Manager. `null` = list only. */
  const [openId, setOpenId] = useState<string | null>(null);
  /**
   * β›”β›” S67-T12: A RULE'S REFUSAL IS RAISED BY SAVE AND WORN BY ITS OWN ROW. The dialog used to
   * compute `rulesRefusal(draft)` on every render, so a stored rule the editor could not represent
   * put a red sentence on the screen the moment the dialog opened, before anybody did anything,
   * and Save then stopped at that first rule and saved nothing. Nothing is judged on open now.
   */
  const [flags, setFlags] = useState<Record<string, string>>({});
  /** The cap's own refusal, which is raised by an ACT rather than by the draft's shape. */
  const [notice, setNotice] = useState("");
  const [colourRefusals, setColourRefusals] = useState<Record<string, string>>({});
  const [reveal, setReveal] = useState<string | null>(null);
  const rows = useRef(new Map<string, HTMLLIElement>());
  const stored = useMemo(() => new Map((rules ?? []).map((r) => [r.id, r] as const)), [rules]);

  useEffect(() => {
    if (!reveal) return;
    rows.current.get(reveal)?.scrollIntoView({ block: "nearest" });
    setReveal(null);
  }, [reveal]);

  const colourRefusal = useCallback((id: string, reason: string) => {
    setColourRefusals((current) => {
      if ((current[id] ?? "") === reason) return current;
      const next = { ...current };
      if (reason) next[id] = reason;
      else delete next[id];
      return next;
    });
  }, []);

  const clearFlag = useCallback((id: string) => {
    setFlags((current) => {
      if (!(id in current)) return current;
      const next = { ...current };
      delete next[id];
      return next;
    });
  }, []);

  const add = useCallback(() => {
    const out = addRule(draft, blankRule(range));
    setNotice(out.refusal ?? "");
    if (out.refusal) return;
    const id = out.rules[out.rules.length - 1].id;
    setDraft(out.rules);
    setOpenId(id);
    setReveal(id);
  }, [draft, range]);

  const patch = useCallback((id: string, next: Partial<SheetRule>) => {
    setNotice("");
    clearFlag(id);
    setDraft((current) => updateRule(current, id, next));
  }, [clearFlag]);

  const flagged = Object.keys(flags).length > 0;

  /**
   * ⭐⭐ S67-T12: SAVE JUDGES EACH RULE ON ITS OWN, AND A BROKEN ONE NEVER HOLDS THE REST HOSTAGE.
   *
   * Only a rule ADDED or CHANGED in this dialog is judged: a rule the tab already stored and
   * nobody touched is saved exactly as it was stored, because the server accepted it and the
   * owner's complaint was a refusal about a rule he "didn't even do anything" to. The first press
   * flags every incomplete edited rule on its own row and saves nothing, so a person sees which
   * rules and why. A press while every incomplete rule is already flagged saves the others: a
   * flagged rule the tab already stored is kept as it was stored (this editor never deletes it),
   * and a flagged rule added in this dialog is left out. A rule that breaks after its row was
   * judged is flagged again rather than dropped unseen.
   */
  const confirm = () => {
    if (Object.values(colourRefusals).some(Boolean)) return;
    const found: Record<string, string> = {};
    for (const rule of draft) {
      const was = stored.get(rule.id);
      if (was && JSON.stringify(was) === JSON.stringify(rule)) continue;
      const why = ruleRefusal(rule);
      if (why) found[rule.id] = why;
    }
    const ids = Object.keys(found);
    if (ids.length === 0) {
      onSave(draft);
      return;
    }
    if (ids.some((id) => flags[id] !== found[id])) {
      setFlags(found);
      setReveal(ids[0]);
      return;
    }
    onSave(draft.flatMap((rule) => {
      if (!found[rule.id]) return [rule];
      const kept = stored.get(rule.id);
      return kept ? [kept] : [];
    }));
  };

  return (
    <ConfirmDialog
      open
      title="Conditional formatting"
      tone="primary"
      cancelLabel="Cancel"
      confirmLabel={flagged ? "Save the other rules" : "Save rules"}
      onCancel={onCancel}
      onConfirm={confirm}
      body={(
        <div className="sheet-rules">
          {/* ⭐⭐ THE ORDER RULE, SAID ON THE SURFACE THAT OWNS IT. Two rules matching one cell is
              ordinary, and a person who cannot see which one wins will reorder at random until
              the sheet looks right. `rules.ts::ruleStyleAt` stops at the first match and takes
              its whole style; this sentence is that behaviour in words. */}
          <p className="sheet-rules-note">
            The first rule that matches a cell paints it, and it paints the whole cell. Move a rule
            up to let it win.
          </p>

          {draft.length === 0 ? (
            <p className="sheet-rules-empty">No rules yet.</p>
          ) : (
            <div className="sheet-rules-table">
              {/* ⭐ S67-T12: EXCEL'S RULES MANAGER COLUMNS, in sentence case (DESIGN.md 2). */}
              <div className="sheet-rules-head" aria-hidden="true">
                <span />
                <span>Rule</span>
                <span>Format</span>
                <span>Applies to</span>
                <span />
              </div>
              <ol className="sheet-rules-list" aria-label="Rules, in the order they apply">
                {draft.map((rule, index) => (
                  <RuleRow
                    key={rule.id}
                    rule={rule}
                    index={index}
                    count={draft.length}
                    open={openId === rule.id}
                    flag={flags[rule.id] ?? ""}
                    stored={stored.has(rule.id)}
                    rowRef={(el) => {
                      if (el) rows.current.set(rule.id, el);
                      else rows.current.delete(rule.id);
                    }}
                    onToggle={() => setOpenId((current) => (current === rule.id ? null : rule.id))}
                    onPatch={patch}
                    onColourRefusal={colourRefusal}
                    onMove={(delta) => {
                      setNotice("");
                      setDraft((current) => moveRule(current, rule.id, delta));
                    }}
                    onRemove={() => {
                      setNotice("");
                      clearFlag(rule.id);
                      setOpenId((current) => (current === rule.id ? null : current));
                      setDraft((current) => removeRule(current, rule.id));
                    }}
                  />
                ))}
              </ol>
            </div>
          )}

          <div className="sheet-rules-foot">
            <button type="button" className="sheet-rules-add" onClick={add}>
              Add a rule
            </button>
            <span className="sheet-rules-count">
              {draft.length} of {MAX_SHEET_RULES}
            </span>
          </div>

          {notice ? (
            <p className="sheet-rules-refusal" role="alert">{notice}</p>
          ) : null}
        </div>
      )}
    />
  );
}

/**
 * ⭐ S67-T12: THE FORMAT COLUMN. The paint a rule lays on a matching cell, drawn small: the fill,
 * the ink and the weight on sample text for a flat rule, the ramp for a colour scale, the bar for a
 * data bar. It reads the DRAFT, so changing a colour in the open editor repaints this at once.
 */
function RulePreview({ rule }: { rule: SheetRule }) {
  const kind = ruleKind(rule);
  if (kind === "scale") {
    return (
      <span className="sheet-rules-preview is-ramp" role="img" aria-label="Colour scale"
        style={{ background: scaleBackground(rule) }} />
    );
  }
  if (kind === "bar") {
    return (
      <span className="sheet-rules-preview is-bar" role="img" aria-label="Data bar">
        <span className="sheet-rules-preview-bar" style={{ background: rulePaint(rule.style?.fill) }} />
      </span>
    );
  }
  const style = rule.style ?? {};
  if (!style.fill && !style.color && style.bold !== true) {
    return <span className="sheet-rules-preview is-none">No format</span>;
  }
  return (
    <span className={"sheet-rules-preview" + (style.bold ? " is-bold" : "")}
      style={{ background: rulePaint(style.fill), color: rulePaint(style.color) }}>
      AaBbCc
    </span>
  );
}

interface RuleRowProps {
  rule: SheetRule;
  index: number;
  count: number;
  open: boolean;
  /** The refusal Save raised for this rule, or `""`. */
  flag: string;
  /** Whether the tab already stored this rule, which decides what saving the others does to it. */
  stored: boolean;
  rowRef: (el: HTMLLIElement | null) => void;
  onToggle: () => void;
  onPatch: (id: string, next: Partial<SheetRule>) => void;
  onColourRefusal: (id: string, reason: string) => void;
  onMove: (delta: number) => void;
  onRemove: () => void;
}

/**
 * ⭐⭐ S67-T12: ONE SUMMARY ROW PER RULE, and the rule's editor opens UNDER its own row only when
 * that row is clicked. The row is a real button (`aria-expanded`), so Enter and Space open it too.
 */
function RuleRow({
  rule, index, count, open, flag, stored, rowRef, onToggle, onPatch, onColourRefusal, onMove,
  onRemove,
}: RuleRowProps) {
  const ids = useId();
  const where = rangeText(rule.range);
  const condition = ruleCondition(rule);
  return (
    <li ref={rowRef}
      className={"sheet-rules-card" + (open ? " is-open" : "") + (flag ? " is-flagged" : "")}>
      <div className="sheet-rules-line">
        <span className="sheet-rules-order" aria-hidden="true">{index + 1}</span>
        <button
          type="button"
          className="sheet-rules-pick"
          aria-expanded={open}
          aria-controls={open ? `${ids}-editor` : undefined}
          aria-describedby={flag ? `${ids}-flag` : undefined}
          aria-label={`Rule ${index + 1}: ${ruleSummary(rule)}`}
          onClick={onToggle}
        >
          <span className="sheet-rules-summary" title={condition}>{condition}</span>
          <RulePreview rule={rule} />
          <span className="sheet-rules-where" title={where}>{where}</span>
        </button>
        <div className="sheet-rules-moves">
          <button
            type="button"
            className="sheet-rules-move"
            aria-label={`Move rule ${index + 1} up`}
            title="Move up"
            disabled={index === 0}
            onClick={() => onMove(-1)}
          >
            <IconChevron />
          </button>
          <button
            type="button"
            className="sheet-rules-move is-down"
            aria-label={`Move rule ${index + 1} down`}
            title="Move down"
            disabled={index === count - 1}
            onClick={() => onMove(1)}
          >
            <IconChevron />
          </button>
          <button
            type="button"
            className="sheet-rules-remove"
            aria-label={`Delete rule ${index + 1}`}
            title="Delete this rule"
            onClick={onRemove}
          >
            <IconRemove />
          </button>
        </div>
      </div>
      {flag ? (
        <p className="sheet-rules-flag" id={`${ids}-flag`}>
          {flag} {stored
            ? "Saving the other rules keeps this one as it was."
            : "Saving the other rules leaves this one out."}
        </p>
      ) : null}
      {open ? (
        <RuleEditor rule={rule} editorId={`${ids}-editor`} onPatch={onPatch}
          onColourRefusal={onColourRefusal} />
      ) : null}
    </li>
  );
}

interface RuleEditorProps {
  rule: SheetRule;
  editorId: string;
  onPatch: (id: string, next: Partial<SheetRule>) => void;
  onColourRefusal: (id: string, reason: string) => void;
}

function RuleEditor({ rule, editorId, onPatch, onColourRefusal }: RuleEditorProps) {
  const ids = useId();
  const kind = ruleKind(rule);
  const arity = ruleArity(rule.op);
  // The OPEN rule's range and any cell its formula names are outlined on the grid
  // (refHighlight.ts). S67-T12: only the open rule, so fifty stored rules no longer outline at once.
  useCellRefHighlight([rangeText(rule.range), kind === "formula" ? String(rule.value ?? "") : ""]);

  /**
   * ⭐⭐ CHANGING THE KIND CHANGES WHAT THE RULE NEEDS TO BE COMPLETE, so it carries those needs
   * with it rather than leaving a half-formed rule the save would refuse with a sentence about a
   * control the card is no longer showing. A scale and a bar both ride `op: "between"`, which is
   * what makes the server persist their two bounds with no new field; a scale gains the default
   * ramp and a bar gains a fill.
   *
   * ⚠ `kind: undefined` IS HOW `cell` IS WRITTEN. It is the default and is stored as an absence
   * (`types.ts::SHEET_RULE_KINDS`), so a rule switched to a scale and back is byte for byte the
   * rule it started as. `JSON.stringify` drops an undefined value, which is what makes that true
   * all the way to the document rather than only in this component.
   */
  const setKind = (next: SheetRuleKind) => {
    if (next === kind) return;
    if (next === "cell") {
      onPatch(rule.id, { kind: undefined });
      return;
    }
    if (next === "formula") {
      onPatch(rule.id, { kind: next, op: "eq", value: "", value2: undefined, scale: undefined });
      return;
    }
    // ⭐ S67-T13: a new colour scale spreads from the lowest to the highest value, Excel's
    // default, and carries no stale bound from the kind it was switched from.
    if (next === "scale") {
      onPatch(rule.id, {
        kind: next,
        op: "between",
        value: undefined,
        value2: undefined,
        scale: {
          ...(rule.scale ?? { low: DEFAULT_RULE_SCALE.low, high: DEFAULT_RULE_SCALE.high }),
          minType: "lowest",
          maxType: "highest",
        },
      });
      return;
    }
    onPatch(rule.id, {
      kind: next,
      op: "between",
      scale: rule.scale,
      style: next === "bar" ? { fill: rule.style?.fill || DEFAULT_BAR_FILL } : rule.style,
    });
  };

  return (
    <div className="sheet-rules-editor" id={editorId}>
      <div className="sheet-rules-row">
        <label className="sheet-rules-field">
          <span className="sheet-rules-label" id={`${ids}-range`}>Applies to</span>
          <input
            className="sheet-rules-input"
            type="text"
            value={rangeText(rule.range)}
            aria-labelledby={`${ids}-range`}
            placeholder="B2:D40"
            onChange={(e) => onPatch(rule.id, { range: e.target.value })}
          />
        </label>
      </div>

      <div className="sheet-rules-row">
        {/* ⭐⭐ W54-T05 β€” THE KIND IS ON THE CARD, NOT HIDDEN BEHIND THE MENU THAT MADE IT. A
            colour scale and a data bar are created from the ribbon's Conditional formatting
            gallery, and an editor that could not represent them would have listed a rule it
            could not describe, or worse, quietly rewritten it into a condition nobody chose. */}
        {/* ⚠ S66-T12: a select field sizes to its longest label (`is-select`), so "Highlight
            cells" and "Is not empty" are never clipped by a shared flex row. */}
        <label className="sheet-rules-field is-select">
          <span className="sheet-rules-label" id={`${ids}-kind`}>Rule</span>
          <select
            className="sheet-rules-select"
            value={kind}
            aria-labelledby={`${ids}-kind`}
            onChange={(e) => setKind(e.target.value as SheetRuleKind)}
          >
            {SHEET_RULE_KINDS.map((entry) => (
              <option key={entry} value={entry}>{RULE_KIND_LABEL[entry]}</option>
            ))}
          </select>
        </label>
        {kind === "cell" ? (
          <label className="sheet-rules-field is-select">
            <span className="sheet-rules-label" id={`${ids}-op`}>Condition</span>
            <select
              className="sheet-rules-select"
              value={rule.op}
              aria-labelledby={`${ids}-op`}
              onChange={(e) => onPatch(rule.id, { op: e.target.value as SheetRuleOp })}
            >
              {RULE_OPS.map((op) => (
                <option key={op} value={op}>{RULE_OP_LABEL[op]}</option>
              ))}
            </select>
          </label>
        ) : null}
        {kind === "formula" ? (
          <label className="sheet-rules-field">
            <span className="sheet-rules-label">Formula</span>
            <input
              className="sheet-field sheet-rules-input"
              type="text"
              value={String(rule.value ?? "")}
              aria-label="Formula"
              placeholder="=$C8<0"
              onChange={(e) => onPatch(rule.id, { op: "eq", value: e.target.value })}
            />
          </label>
        ) : null}
        {kind === "scale" ? (
          <>
            <ScaleEndFields rule={rule} which="min" onPatch={onPatch} />
            <ScaleEndFields rule={rule} which="max" onPatch={onPatch} />
          </>
        ) : null}
        {kind !== "formula" && kind !== "scale" && arity >= 1 ? (
          <label className="sheet-rules-field">
            <span className="sheet-rules-label" id={`${ids}-value`}>
              {arity === 2 ? "From" : "Value"}
            </span>
            <input
              className="sheet-rules-input"
              type="text"
              value={String(rule.value ?? "")}
              aria-labelledby={`${ids}-value`}
              onChange={(e) => onPatch(rule.id, { value: e.target.value })}
            />
          </label>
        ) : null}
        {kind !== "formula" && kind !== "scale" && arity === 2 ? (
          <label className="sheet-rules-field">
            <span className="sheet-rules-label" id={`${ids}-value2`}>To</span>
            <input
              className="sheet-rules-input"
              type="text"
              value={String(rule.value2 ?? "")}
              aria-labelledby={`${ids}-value2`}
              onChange={(e) => onPatch(rule.id, { value2: e.target.value })}
            />
          </label>
        ) : null}
      </div>

      {/* β›” THE PALETTE IS TOKEN NAMES (`rules.ts::RULE_FILLS` / `RULE_INKS`), the ribbon's own,
          so a palette change repaints every rule ever written. `var(--lp-*)` in the swatch is a
          token reference and never a hue (DESIGN.md 3). */}
      {/* ⭐ A SCALE CHOOSES A RAMP, NOT A COLOUR. Its two ends are what the document stores
          (`scale: {low, high}`) and the bands between them are looked up from those two names, so
          a person picks the ramp whole rather than assembling one end at a time and being left
          with a scale that runs from red to red. */}
      {kind === "scale" ? (
        <div className="sheet-rules-row sheet-rules-paint">
          <span className="sheet-rules-label">Scale</span>
          <div className="sheet-rules-swatches" role="group" aria-label="Colour scale">
            {RULE_SCALES.map((ramp) => {
              const on = rule.scale?.low === ramp.low && rule.scale?.high === ramp.high;
              return (
                <button
                  key={ramp.id}
                  type="button"
                  className={"sheet-rules-swatch" + (on ? " is-on" : "")}
                  style={{ background: rampBackground(ramp.bands) }}
                  aria-label={ramp.label}
                  aria-pressed={on}
                  title={ramp.label}
                  onClick={() => onPatch(rule.id, {
                    scale: { ...rule.scale, low: ramp.low, high: ramp.high },
                  })}
                />
              );
            })}
          </div>
        </div>
      ) : null}

      {/* ⚠ A SCALE PAINTS FROM ITS RAMP AND FROM NOTHING ELSE, so it is offered no flat fill,
          no ink and no weight: a control that wrote a key `ruleStyleAt` never reads for that kind
          is the fake affordance the ribbon's own contract refuses by name. A BAR keeps the fills,
          because a bar's colour IS its rule's fill, and loses the ink and the weight for the same
          reason. */}
      {kind === "bar" ? (
      <div className="sheet-rules-row sheet-rules-paint">
        <span className="sheet-rules-label">Bar</span>
        <div className="sheet-rules-swatches" role="group" aria-label="Fill colour">
          {RULE_FILLS.map((entry) => (
            <button
              key={entry.token}
              type="button"
              className={"sheet-rules-swatch" + (rule.style?.fill === entry.token ? " is-on" : "")}
              style={{ background: `var(${entry.token})` }}
              aria-label={`${entry.label} fill`}
              aria-pressed={rule.style?.fill === entry.token}
              title={`${entry.label} fill`}
              onClick={() => onPatch(rule.id, {
                style: {
                  ...rule.style,
                  fill: rule.style?.fill === entry.token ? undefined : entry.token,
                },
              })}
            />
          ))}
        </div>
      </div>
      ) : null}
      {kind === "cell" || kind === "formula" ? (
        <div className="sheet-rules-field" role="group" aria-label="Paint">
          <div className="sheet-rules-row sheet-rules-paint">
            <span className="sheet-rules-label">Paint</span>
            <button
              type="button"
              className={"sheet-rules-bold" + (rule.style?.bold ? " is-on" : "")}
              aria-pressed={rule.style?.bold === true}
              aria-label="Bold"
              title="Bold"
              onClick={() => onPatch(rule.id, {
                style: { ...rule.style, bold: rule.style?.bold ? undefined : true },
              })}
            >
              B
            </button>
          </div>
          <RuleColourControl rule={rule} which="color" label="Font colour"
            palette={RULE_INKS} onPatch={onPatch} onRefusal={onColourRefusal} />
          <RuleColourControl rule={rule} which="fill" label="Fill colour"
            palette={RULE_FILLS} onPatch={onPatch} onRefusal={onColourRefusal} />
        </div>
      ) : null}
    </div>
  );
}

/**
 * ⭐⭐ S67-T13: ONE END OF A COLOUR SCALE, AS EXCEL'S RULES MANAGER EDITS IT. A type picker
 * (Lowest value / Highest value, Number, Percent, Percentile) and, unless the end is measured
 * from the data, the number that type needs. It reads through `rules.ts::scaleEnds`, so an
 * imported boundless scale opens as lowest to highest with nothing to fix.
 *
 * ⚠ TYPING PINS THE TYPE. A legacy scale's `number` end is read from its stored number, so
 * clearing that box without pinning would flip the end back to lowest under the cursor and hide
 * the box being typed in.
 */
function ScaleEndFields({ rule, which, onPatch }: {
  rule: SheetRule;
  which: "min" | "max";
  onPatch: RuleEditorProps["onPatch"];
}) {
  const ids = useId();
  const ends = scaleEnds(rule);
  const end = which === "min" ? ends.min : ends.max;
  const measured: SheetRuleScaleType = which === "min" ? "lowest" : "highest";
  const offered = which === "min" ? RULE_SCALE_MIN_TYPES : RULE_SCALE_MAX_TYPES;
  const options = offered.includes(end.type) ? offered : [...offered, end.type];
  const name = which === "min" ? "Minimum" : "Maximum";
  const raw = which === "min" ? rule.value : rule.value2;
  const scale = rule.scale ?? { low: DEFAULT_RULE_SCALE.low, high: DEFAULT_RULE_SCALE.high };
  const withType = (type: SheetRuleScaleType) => (
    which === "min" ? { ...scale, minType: type } : { ...scale, maxType: type }
  );
  const withValue = (value: string | undefined): Partial<SheetRule> => (
    which === "min" ? { value } : { value2: value }
  );
  return (
    <>
      <label className="sheet-rules-field is-select">
        <span className="sheet-rules-label" id={`${ids}-type`}>{name}</span>
        <select
          className="sheet-rules-select"
          value={end.type}
          aria-labelledby={`${ids}-type`}
          onChange={(e) => {
            const type = e.target.value as SheetRuleScaleType;
            onPatch(rule.id, {
              scale: withType(type),
              ...(type === measured ? withValue(undefined) : {}),
            });
          }}
        >
          {options.map((type) => (
            <option key={type} value={type}>{RULE_SCALE_TYPE_LABEL[type]}</option>
          ))}
        </select>
      </label>
      {end.type !== "lowest" && end.type !== "highest" ? (
        <label className="sheet-rules-field">
          <span className="sheet-rules-label" id={`${ids}-value`}>Value</span>
          <input
            className="sheet-rules-input"
            type="text"
            inputMode="decimal"
            value={String(raw ?? "")}
            aria-label={`${name} value`}
            placeholder={end.type === "number" ? "" : "0 to 100"}
            onChange={(e) => onPatch(rule.id, {
              scale: withType(end.type),
              ...withValue(e.target.value),
            })}
          />
        </label>
      ) : null}
    </>
  );
}

type RuleColourInput = HTMLInputElement & { lpApplyColour?: (value: string) => void };

// The ribbon uses native change: React onChange maps to input and would patch on every drag.
// Refresh the callback on each render, but bind only once to each mounted input.
const bindRuleColour = (apply: (value: string) => void) => (el: RuleColourInput | null) => {
  if (!el) return;
  el.lpApplyColour = apply;
  if (el.dataset.lpColourBound === "1") return;
  el.dataset.lpColourBound = "1";
  el.addEventListener("change", () => el.lpApplyColour?.(el.value.toLowerCase()));
};

function RuleColourControl({ rule, which, label, palette, onPatch, onRefusal }: {
  rule: SheetRule;
  which: "color" | "fill";
  label: string;
  palette: readonly { token: string; label: string }[];
  onPatch: RuleEditorProps["onPatch"];
  onRefusal: RuleEditorProps["onColourRefusal"];
}) {
  const id = useId();
  const chosen = rule.style?.[which];
  const custom = chosen?.startsWith("#") ? chosen.toLowerCase() : "";
  const [hex, setHex] = useState(custom);
  const [refusal, setRefusal] = useState("");
  useEffect(() => {
    setHex(custom);
    setRefusal("");
    onRefusal(id, "");
  }, [custom, id, onRefusal]);
  useEffect(() => {
    return () => onRefusal(id, "");
  }, [id, onRefusal]);

  const report = (reason: string) => {
    setRefusal(reason);
    onRefusal(id, reason);
  };
  const hexRefusal = (value: string) => {
    const colour = value.trim().toLowerCase();
    return colour.startsWith("#") && new RegExp(CELL_COLOUR_PATTERN).test(colour)
      ? "" : "Use a six digit hex colour, such as #C8A24B.";
  };

  const choose = (colour: string | undefined) => {
    setHex(colour?.startsWith("#") ? colour : "");
    report("");
    onPatch(rule.id, { style: { ...rule.style, [which]: colour } });
  };
  const commitHex = (value: string) => {
    const reason = hexRefusal(value);
    if (reason) {
      report(reason);
      return;
    }
    choose(value.trim().toLowerCase());
  };

  return (
    <div className="sheet-rules-field" role="group" aria-labelledby={`${id}-label`}>
      <div className="sheet-rules-row sheet-rules-paint">
        <span className="sheet-rules-label" id={`${id}-label`}>{label}</span>
        <button type="button" className="sheet-rules-add" aria-pressed={!chosen}
          onClick={() => choose(undefined)}>None</button>
      </div>
      <div className="sheet-rules-row sheet-rules-paint">
        <div className="sheet-rules-swatches">
          {palette.map((entry) => (
            <button key={entry.token} type="button"
              className={"sheet-rules-swatch" + (which === "color" ? " is-ink" : "")
                + (chosen === entry.token ? " is-on" : "")}
              style={which === "color" ? { color: `var(${entry.token})` }
                : { background: `var(${entry.token})` }}
              aria-label={`${entry.label} ${which === "color" ? "text" : "fill"}`}
              aria-pressed={chosen === entry.token}
              title={entry.label}
              onClick={() => choose(chosen === entry.token ? undefined : entry.token)}
            >
              {which === "color" ? "A" : null}
            </button>
          ))}
        </div>
        <label className="sheet-rules-row sheet-rules-paint">
          <input type="color"
            key={chosen || "none"}
            className={"sheet-ribbon-custom-input sheet-rules-swatch" + (custom ? " is-on" : "")}
            aria-label={`Custom ${label.toLowerCase()}`}
            title={custom || "Choose a custom colour"}
            style={{ background: custom || undefined }}
            defaultValue={custom || (which === "color" ? "#000000" : "#ffffff")}
            ref={bindRuleColour(commitHex)}
          />
          <span className="sheet-rules-label">Custom</span>
        </label>
      </div>
      <div className="sheet-rules-field">
          <input type="text" className="sheet-rules-input" aria-label={`${label} hex`}
            aria-invalid={Boolean(refusal)} aria-describedby={refusal ? `${id}-refusal` : undefined}
            value={hex} placeholder="#rrggbb" spellCheck={false}
            onChange={(e) => {
              // The dialog learns of a half typed colour at once, so Save cannot slip past it, but
              // the line itself only appears on commit (blur or Enter), never mid word.
              const reason = e.target.value === custom ? "" : hexRefusal(e.target.value);
              setHex(e.target.value);
              onRefusal(id, reason);
              if (!reason) setRefusal("");
            }}
            onBlur={() => { if (hex !== custom) commitHex(hex); }}
            onKeyDown={(e) => {
              if (e.key === "Enter") { e.preventDefault(); commitHex(hex); }
            }}
          />
      </div>
      {refusal ? <p className="sheet-rules-refusal" id={`${id}-refusal`} role="alert">{refusal}</p> : null}
    </div>
  );
}

// ── the validation list editor ────────────────────────────────────────────────────────────────

export interface ValidationDialogProps {
  open: boolean;
  /** How many cells the list is about to be set on, so the title can say what it will change. */
  count: number;
  /** The list the anchor cell carries today, or an empty array. */
  list: readonly string[];
  onCancel: () => void;
  onSave: (list: string[]) => void;
}

/** The same `open` split, for the same reason: the draft starts from the cell every time. */
export function ValidationDialog({ open, count, list, onCancel, onSave }: ValidationDialogProps) {
  if (!open) return null;
  return <ValidationSurface count={count} list={list} onCancel={onCancel} onSave={onSave} />;
}

function ValidationSurface({ count, list, onCancel, onSave }: Omit<ValidationDialogProps, "open">) {
  const [text, setText] = useState(() => listText(list));
  const [notice, setNotice] = useState("");
  const boxId = useId();
  const parsed = parseList(text);

  return (
    <ConfirmDialog
      open
      title="Values this cell accepts"
      tone="primary"
      cancelLabel="Cancel"
      confirmLabel="Save list"
      onCancel={onCancel}
      onConfirm={() => {
        const out = parseList(text);
        if (out.refusal) {
          setNotice(out.refusal);
          return;
        }
        onSave(out.list);
      }}
      body={(
        <div className="sheet-validation">
          <label className="sheet-validation-label" htmlFor={boxId}>
            One value per line. {count === 1 ? "This cell" : `These ${count} cells`} will offer them
            as a dropdown and refuse anything else.
          </label>
          <textarea
            id={boxId}
            className="sheet-validation-box"
            rows={8}
            spellCheck={false}
            autoFocus
            value={text}
            placeholder={"Royal\nFisch"}
            onChange={(e) => { setNotice(""); setText(e.target.value); }}
          />
          <p className="sheet-validation-count">
            {parsed.refusal ? "" : `${parsed.list.length} of ${MAX_VALIDATION_LIST} values.`}
            {parsed.list.length === 0 && !parsed.refusal
              ? " Saving an empty list removes the dropdown."
              : ""}
          </p>
          {notice || parsed.refusal ? (
            <p className="sheet-validation-refusal" role="alert">{notice || parsed.refusal}</p>
          ) : null}
        </div>
      )}
    />
  );
}