File size: 54,297 Bytes
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5981db
2183dbe
 
a5981db
2183dbe
 
 
a5981db
2183dbe
 
 
 
 
 
7f72224
85f794d
 
 
7f72224
2183dbe
 
 
81a8217
e88a3a3
9e15897
f5696cb
c920df3
85f794d
daae64a
3ae85d8
2183dbe
 
 
7f72224
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5696cb
 
 
 
 
 
 
c920df3
 
 
 
 
 
85f794d
 
 
 
 
daae64a
 
 
 
 
 
 
e88a3a3
 
 
 
 
 
 
 
9e15897
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
cfa8541
 
 
 
 
 
 
 
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2183dbe
 
a5981db
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
a5981db
2183dbe
 
 
 
 
 
a5981db
 
2183dbe
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
2183dbe
 
 
a5981db
 
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
2183dbe
 
 
 
 
 
c72f0a1
 
 
 
81a8217
2183dbe
c72f0a1
85f794d
c72f0a1
 
 
 
 
071ce2b
c72f0a1
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
7f72224
a5981db
7f72224
2183dbe
7f72224
 
2183dbe
 
c72f0a1
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
85f794d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f72224
2183dbe
 
 
c72f0a1
2183dbe
 
 
 
 
 
 
7f72224
c72f0a1
2183dbe
c72f0a1
 
 
2183dbe
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
2183dbe
 
 
85f794d
 
2183dbe
 
 
 
 
 
 
 
 
071ce2b
 
 
 
 
 
 
 
 
 
 
 
 
2183dbe
 
 
85f794d
c72f0a1
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d60127
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
2183dbe
071ce2b
 
2183dbe
 
035e397
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
071ce2b
2183dbe
 
035e397
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
2183dbe
 
 
 
85f794d
 
2183dbe
 
 
 
c72f0a1
2183dbe
 
 
 
 
 
c72f0a1
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
2183dbe
 
 
 
 
 
 
 
c72f0a1
85f794d
2183dbe
 
 
 
 
85f794d
2183dbe
 
 
 
c72f0a1
 
85f794d
c72f0a1
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
0e600b9
 
 
 
 
 
 
2183dbe
85f794d
 
7f72224
 
 
 
 
 
2183dbe
 
 
c72f0a1
 
 
2183dbe
 
c72f0a1
 
2183dbe
 
c72f0a1
2183dbe
 
 
 
 
 
f5696cb
e88a3a3
 
 
 
 
9e15897
c920df3
2183dbe
 
85f794d
daae64a
2183dbe
81a8217
2183dbe
 
 
 
3998487
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e600b9
2183dbe
 
 
 
 
 
0e600b9
2183dbe
 
 
 
 
c920df3
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
2183dbe
 
 
 
 
 
e88a3a3
 
 
85f794d
 
 
e88a3a3
85f794d
 
 
 
c920df3
85f794d
daae64a
2183dbe
 
 
 
 
 
 
 
 
3ae85d8
 
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
85f794d
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
2183dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
2183dbe
 
 
85f794d
2183dbe
 
 
 
 
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
// ---------------------------------------------------------------------------
// settings / SettingsModal.tsx β€” EXIT wave 2 (W2-8, contract Y4).
//
// Settings and Manage users as ONE centred modal with a left rail, matching the
// shipped Streamlit design (`app.py:settings_dialog`, item 8) and the reference
// the owner named: *"when I click 'Setting' this whole thing pops up? I want
// that exact thing for when we click Settings and Manage User, where the
// background is clearly blurred too."*
//
// ⚠ WAVE 19 R12 β€” THE SURFACE IS CALLED "SETTINGS" AGAIN, and this note replaces
// the wave-15 one that said the opposite ("the surface is called PROFILE now, in
// this shell only"). The owner has ruled the rename back: one account-menu row,
// called Settings, with a gear, shown to everyone, landing on Account. The file,
// the export and the `SettingsSection` type were never renamed in either
// direction β€” which is exactly why the wave-15 trade was the right one to make
// and the cheap one to undo. A LABEL moved twice; no import ever did.
//
// β›” `verify_ui.py`'s naming check enforced the wave-15 wording, so the correct
// edit would have turned it red. It is inverted in the same change (bare
// "Profile" must not survive as copy; bare "Settings" must be PRESENT) and
// booked as wave-19 amendment 1. A gate that pins a superseded ruling is not a
// gate, it is a second place the old decision lives.
//
// A MODAL, NOT A PAGE, and the shipped version's reasoning holds here too:
// settings are a detour, not a destination β€” you change a toggle and go back to
// what you were doing. The Streamlit app kept a settings PAGE alongside the
// modal because a deep link is a poor thing to land on a modal; the shell has
// no settings route at all, so there is nothing to keep.
//
// β›” EVERY ADMIN CONTROL HERE IS A COURTESY, NOT A CHECK. The server refuses a
// non-admin on every `/admin/*` route, fail-closed, and Y4's gate proves it by
// having a viewer try. Hiding the rail entry only spares a member a door that
// would not open.
// ---------------------------------------------------------------------------

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
// ⭐ W37-T05 β€” the shared in-flight label; see `ui/Busy.tsx` for why it is a component.
import { Busy } from "../ui/Busy";
import { useOverlayLayer } from "../customer-grid/OverlaySurface";
import type { ReactNode } from "react";
import type { SessionUser } from "../shell/session";
import { isAdmin, parseUserEnvelope } from "../shell/session";
import type { AdminUser, SettingsPayload } from "./settingsApi";
// ⚠ `patchUser` and `setPassword` left this file with `EditUser` (R7) β€” they are
// imported by `PermsEditor` now, where the form that writes them lives, and it
// spells the patch shape `Parameters<typeof patchUser>[1]` rather than importing
// `UserPatch` separately. `noUnusedLocals` is what walks a move like this down to
// the last orphaned import, which is the tsconfig earning its keep again.
import { clearAvatar, createUser, getSettings, listUsers, setAvatar } from "./settingsApi";
import { TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract";
// S85-T157: the member view's read-only flag. The server refuses every write while it is on;
// this file disables its own write controls so none is offered.
import { startViewAs, viewAsActive } from "./viewAs";
import "../styles/sdlc80/connector-setup.css";
import { PermsEditor } from "./PermsEditor";
// Wave 19 contract C2 β€” session D's self-contained plane; see the mount below.
import { AdminPane } from "./AdminPane";
// Sheet shortcuts use a self-contained client preference pane.
import ShortcutSettings from "./ShortcutSettings";
import NotifyDestinations from "./NotifyDestinations";
import SecurityPane from "./SecurityPane";
import ActivityLogPage from "./ActivityLogPage";
import UsagePane from "./UsagePane";
import BrandPane from "./BrandPane";
import OperatorPage from "../operator/OperatorPage";
/* β›” `StatementsPane` LEFT WITH ITS RAIL ROW (wave 35 Β· T38): the file is DELETED, not merely
   unmounted. An orphaned component with no importer is the shape this repo books as
   [[artifact-with-no-importer]] β€” it reads to the next person as a surface that still exists. */
import { moduleSummary, parseEntry, reachableSection, retiredSettingsRoute } from "./permsModel";

// The vocabulary lives beside the rule that gates it (permsModel), and is
// re-exported here so `Shell.tsx`'s import does not have to know that.
export type { SettingsSection } from "./permsModel";
import type { SettingsSection } from "./permsModel";

// β›” `BU_LABELS`, `BU_IDS` and `scopeWords` ALL WENT WITH THE PICKER (R1).
// Nothing offers, writes or RENDERS a business unit in this shell any more β€”
// the last reader was the accounts list, and its column is now "Access". The
// concept survives only as a legacy value on the record, which S1's migration
// converts to a permanent filter once. `noUnusedLocals` is what walked the
// removal down to the last orphan, which is the tsconfig earning its keep.

function moduleWords(mods: string[] | "all"): string {
  // ⚠ `[]` READS as unrestricted β€” the existing semantic Y4 says not to "fix"
  // this wave. Saying "All modules" here is therefore the TRUE statement, and
  // the write side is what refuses to create the ambiguity (see settingsApi).
  if (mods === "all" || !Array.isArray(mods) || mods.length === 0) return "All modules";
  return `${mods.length} module${mods.length === 1 ? "" : "s"}: ${mods.join(", ")}`;
}

// ------------------------------------------------------------------ the users pane

/** The trailing affordance on an account card. SVG, never a character glyph. */
function ChevIcon() {
  return (
    <svg className="set-acct-chev" viewBox="0 0 12 12" aria-hidden="true">
      <path d="M4.4 2.4 8 6l-3.6 3.6" />
    </svg>
  );
}

// ── WAVE 19 R13: one mark per rail tab ───────────────────────────────────────
//
// A mark per row makes each Settings section recognisable without reading the whole rail.
//
// ⚠ PURE FUNCTIONS OF NOTHING, and that is a requirement here rather than a
// style: `verify_ui.py` renders this module through `react-dom/server`, where
// `window` and `document` do not exist. An icon that measured anything, or read
// a theme off the DOM at module scope, would take the whole gate down with it β€”
// and the failure would look like a broken gate rather than a broken icon.
// SVG only, never emoji (the platform's own standing rule).
function RailIcon({ children }: { children: ReactNode }) {
  return (
    <svg className="set-rail-icon" viewBox="0 0 16 16" aria-hidden="true">
      {children}
    </svg>
  );
}

/** Account β€” the person whose settings these are. */
const IconAccount = (
  <RailIcon>
    <circle cx="8" cy="5.6" r="2.7" />
    <path d="M2.9 13.4c0-2.5 2.3-4.1 5.1-4.1s5.1 1.6 5.1 4.1" />
  </RailIcon>
);
/** Your access β€” a closed padlock: what this account may open, and what narrows it. */
const IconAccess = (
  <RailIcon>
    <rect x="3.3" y="7.1" width="9.4" height="6.3" rx="1.3" />
    <path d="M5.6 7.1V5.3a2.4 2.4 0 0 1 4.8 0v1.8" />
  </RailIcon>
);
/** Security - a shield protects the credential; access already wears the padlock. */
const IconSecurity = (
  <RailIcon>
    <path d="M8 1.8 13 3.9v4.2c0 2.7-2.1 4.6-5 6.1-2.9-1.5-5-3.4-5-6.1V3.9z" />
    <path d="m5.5 7.9 1.7 1.7 3.4-3.4" />
  </RailIcon>
);
const IconActivity = (
  <RailIcon>
    <circle cx="8" cy="8" r="5.6" />
    <path d="M8 4.5V8l2.6 1.6" />
  </RailIcon>
);
const IconUsage = (
  <RailIcon>
    <path d="M2.5 13.5h11M4 11V7m4 4V2.5m4 8.5V5" />
  </RailIcon>
);
const IconBrand = (
  <RailIcon>
    <rect x="2" y="2" width="12" height="12" rx="2" />
    <circle cx="5.5" cy="5.5" r="1" />
    <path d="m3 12 3-3 2 2 3-4 2 3" />
  </RailIcon>
);
/** Sheet shortcuts β€” a small keyboard: a row of keys above a spacebar, not the padlock
 *  "Your access" already wears (two authority glyphs in one rail would drift together). */
const IconShortcuts = (
  <RailIcon>
    <rect x="2.3" y="4.6" width="11.4" height="7.6" rx="1.3" />
    <path d="M4.7 7.1h.01M7.3 7.1h.01M9.9 7.1h.01M12.5 7.1h.01M5.5 9.6h5" />
  </RailIcon>
);
const IconNotifications = (
  <RailIcon>
    <path d="M3 11h10l-1.5-2V6a3.5 3.5 0 0 0-7 0v3zM6.5 13a1.5 1.5 0 0 0 3 0" />
  </RailIcon>
);
/** Manage users β€” more than one person. */
const IconUsers = (
  <RailIcon>
    <circle cx="6.2" cy="5.9" r="2.3" />
    <path d="M1.9 13.2c0-2.2 1.9-3.5 4.3-3.5s4.3 1.3 4.3 3.5" />
    <path d="M10.7 4.1a2.3 2.3 0 0 1 0 4.3M11.6 9.9c1.5.4 2.5 1.5 2.5 3.3" />
  </RailIcon>
);
/* β›” `IconMail` LEFT WITH THE STATEMENTS ROW IT DREW (wave 35 Β· T38). `noUnusedLocals` is what
   turns forgetting this half into a build error rather than into a glyph nobody renders, which is
   the type system doing the sweeping. */
/**
 * W63-T06 compatibility descriptor for consumers that still identify the promoted pane by its
 * W62 Settings vocabulary. It is metadata only: the Settings `rail` and pane switch below contain
 * neither this tuple nor a mount. The live door is the shell's single AI API chrome route.
 */
const IconExternal = (
  <RailIcon>
    <path d="M5.3 4.1h-2v7.8h2M10.7 4.1h2v7.8h-2M7 3.2 5.8 12.8M10.2 3.2 9 12.8" />
  </RailIcon>
);
export const PROMOTED_AI_API_COMPATIBILITY = {
  legacyRail: ["external", "AI API", IconExternal],
  component: "ExternalAccessPane",
} as const;
/** Loopable admin β€” stacked plates, i.e. MANY tenants. Deliberately not another
 *  lock or shield: "Your access" already wears a padlock, and two authority
 *  glyphs in one rail would read as two grades of the same thing rather than as
 *  a different scope entirely. */
const IconTenants = (
  <RailIcon>
    <path d="M8 1.9 14.3 5 8 8.1 1.7 5z" />
    <path d="M2.4 8.1 8 10.9l5.6-2.8M2.4 11.2 8 14l5.6-2.8" />
  </RailIcon>
);

/** Disables every control in a pane while viewing as a member. A fieldset is the native fence for
 *  a group of controls, so no pane has to learn the mode. */
function ReadOnlyFence({ readOnly, children }: { readOnly: boolean; children: ReactNode }) {
  if (!readOnly) return <>{children}</>;
  return (
    <fieldset className="set-viewas-lock" disabled>
      {children}
    </fieldset>
  );
}

/** S85-T157: an administrator may view as an active member, never as an admin or as themselves. */
function mayViewAs(viewer: SessionUser, row: AdminUser, readOnly: boolean): boolean {
  const self = viewer.username.trim().toLowerCase();
  return !readOnly && isAdmin(viewer) && row.role === "user" && row.active
    && row.username.trim().toLowerCase() !== self;
}

function UsersPane({ user, readOnly }: { user: SessionUser; readOnly: boolean }) {
  const [users, setUsers] = useState<AdminUser[] | null>(null);
  const [error, setError] = useState("");
  const [denied, setDenied] = useState(false);
  const [notice, setNotice] = useState("");
  /**
   * ⚠ WAVE 17 R7 β€” ONE STATE, WHERE THERE WERE TWO. This pane held `editing`
   * (the inline account-details card, at the BOTTOM of the list) and `permsFor`
   * (the full-pane access page) as separate things, on the wave-15 reasoning
   * that *"they are two different jobs: one changes who the account IS, the
   * other changes what it may SEE"*. True about the data, wrong about the
   * person: an admin opening an account does not know in advance which of the
   * two they came for, and the product offered them two doors, one of which
   * scrolled the page instead of changing it. The owner met that as *"Edit and
   * clicking a user name should just be the EXACT same opening of a full page
   * so its not confusing"*. There is one door now, and one thing behind it.
   */
  const [open, setOpen] = useState<string | null>(null);

  const reload = useCallback(() => {
    setUsers(null);
    setError("");
    setDenied(false);
    void listUsers().then((r) => {
      if (r.ok) {
        setUsers(r.data.users ?? []);
        setError("");
      } else {
        setUsers([]);
        if (r.status === 403) setDenied(true);
        else setError(r.message);
      }
    });
  }, []);

  useEffect(reload, [reload]);

  // wave17 item 3 (R6). ⚠ `.pg-empty` was the WRONG BOX as well as the wrong
  // words: it is the dashed empty-state frame, so a list that was merely still
  // arriving was drawn in the chrome that means "there is nothing here".
  if (users === null)
    return (
      <div className="set-pane set-users">
        <h3 className="set-h">Manage users</h3>
        <div className="set-skeleton" role="status" aria-label="Loading users" aria-busy="true">
          <span className="set-skeleton-line" aria-hidden="true" />
          <span className="set-skeleton-line" aria-hidden="true" />
          <span className="set-skeleton-line" aria-hidden="true" />
        </div>
      </div>
    );

  if (denied)
    return (
      <div className="set-pane set-users">
        <h3 className="set-h">Manage users</h3>
        <p className="set-notice" role="status">You do not have permission to manage users.</p>
      </div>
    );

  // The FULL-PANE TAKEOVER: the users pane IS the modal body, so returning the
  // page here replaces the whole body and nothing else has to know. The rail
  // stays β€” it is chrome, not body, and an admin who wants out of this page
  // entirely should not have to find a Back button first.
  if (open) {
    const who = users.find((u) => u.username === open);
    // The record can genuinely vanish under an open page: `reload()` runs after
    // every write, and another admin may have removed the account in between.
    // Saying so beats rendering a page about nobody.
    if (!who) {
      return (
        <div className="set-pane">
          <section className="set-card">
            <h4 className="set-h4">That account is no longer listed</h4>
            <p className="set-help">It may have been removed since this list was loaded.</p>
            <div className="set-actions">
              <button type="button" className="set-secondary" onClick={() => setOpen(null)}>
                Back to accounts
              </button>
            </div>
          </section>
        </div>
      );
    }
    return (
      <PermsEditor
        // Remount per account: the page holds a DRAFT of somebody's permissions
        // and an unsaved display name, and carrying either across a switch of
        // subject is how one account's edits get saved onto another.
        key={who.username}
        user={who}
        // ⚠ TWO LISTS, TWO JOBS, AND MIXING THEM MAKES A WRONG URL. These are
        // DISPLAY NAMES, for `user`-typed filter conditions β€” the cells hold
        // names, so the builder must offer names. `copyTargets` below carries
        // the RECORDS, because a copy addresses accounts by USERNAME.
        userOptions={users.map((u) => u.name || u.username)}
        copyTargets={users.filter((u) => u.username !== who.username)}
        onBack={() => setOpen(null)}
        // ⚠ IT DOES NOT CLOSE THE PAGE ON EVERY SAVE. Wave 15's version returned
        // to the list on ANY save, which was right when this was only an access
        // editor. It is one page with several things to save now, and a page
        // that ejects you after the first of them is a page you have to
        // re-open to finish the job. The way out stays visible instead.
        // ⭐ W37-T05 QUALIFIES THAT, IT DOES NOT REVERSE IT: the ACCESS save β€” the
        // page's terminal action β€” now passes `back` and does return, because the
        // owner reported being "left on the same pane wondering" after exactly
        // that one. Every other write still leaves you where you are.
        onSaved={(msg, back) => {
          setNotice(msg);
          setError("");
          reload();
          // ⭐ WAVE 37 Β· T05 β€” AND THE PARAGRAPH ABOVE IS NOW HALF TRUE, so it is corrected rather
          // than left to contradict the code. Wave 17's R7 removed the automatic return and its
          // reason still holds for every OTHER write on this pane; the owner's item this wave names
          // the ACCESS save specifically, which is the page's terminal action. So the return is
          // opt-in per write, not restored wholesale: `back` is passed by exactly one caller.
          // ⚠ `reload()` first, then leave β€” the list the admin lands on must show what they
          // just saved, and a navigation that raced the refetch would show the old row.
          if (back) setOpen(null);
        }}
      />
    );
  }

  return (
    <div className="set-pane set-users">
      {/* ⚠ WAVE 19 (owner item 9) β€” THE HEADING MATCHES THE RAIL ENTRY THAT
          OPENS IT. It said "Accounts" while the only way in was a tab reading
          "Manage users", so the pane appeared to be somewhere other than the
          place that was clicked β€” the cheapest kind of "am I in the right
          screen?" there is. The rail is the name; the body agrees with it. */}
      <h3 className="set-h">Manage users</h3>
      {error ? <div className="set-error" role="alert">
        <span title={error}>Could not load or update this account list.</span>
        <button type="button" className="set-secondary" onClick={reload}>Retry</button>
      </div> : null}
      {notice ? <p className="set-notice" role="status">{notice}</p> : null}

      <AddUser
        disabled={readOnly}
        onCreated={(msg) => {
          setNotice(msg);
          setError("");
          reload();
        }}
        onError={(text) => window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text, tone: "error" } }))}
      />

      {users.length === 0 && !error ? (
        <p className="pg-empty">No accounts are configured on this deployment yet.</p>
      ) : (
        /* ⚠ WAVE 17 R7 β€” A LIST OF CARDS, NOT A TABLE, and the shape is the
           feature. The owner asked to "click the whole user's Card, not just
           name, so it has bigger hit box": in a table the only click target
           that could exist was the name itself, because a `<tr onClick>` is
           invisible to a keyboard and wrapping every cell in a button is five
           tab stops per row. One `<button>` per account is ONE control with the
           whole card as its hit box, focusable and Enter-able for free.
           β›” "Business units" IS STILL GONE (R1) and did not come back as a
           card line. What replaced it is the access sentence, which is a page
           now rather than a cell because a permanent filter does not fit in
           one. */
        // R252 supersedes the card layout. Each row keeps one keyboard destination and a full-row pointer target.
        <div className="set-users-table-wrap">
        <table className="set-table set-users-table" role="table" aria-label="Manage users">
          <thead role="rowgroup"><tr role="row"><th scope="col">Name</th><th scope="col">Role</th><th scope="col">Access summary</th><th scope="col">Last active</th></tr></thead>
          <tbody role="rowgroup">
          {users.map((u) => (
            <tr key={u.username} role="row" className={u.active ? "" : "is-inactive"} onClick={() => setOpen(u.username)}>
              <td role="cell">
              <button
                type="button"
                className="set-users-name"
                data-member={u.username}
                onClick={() => setOpen(u.username)}
              >
                <Monogram name={u.name || u.username} />
                <span className="set-acct-body">
                  <span className="set-acct-top">
                    <span className="set-acct-name">{u.name || u.username}</span>
                    {u.active ? null : <span className="set-chip set-chip--off">Deactivated</span>}
                  </span>
                  <span className="set-acct-sub">{u.username}</span>
                  {/* ⚠ An admin BYPASSES perms entirely (C-PERM amendment 4) β€”
                      the clause that also keeps break-glass alive during a
                      store outage. Saying "Everything (admin)" rather than
                      rendering a rule prevents the one dangerous misreading:
                      that the restrictions on an admin's access page are in
                      force. */}
                </span>
                <span className="set-acct-go">Edit<ChevIcon /></span>
              </button>
              </td>
              <td role="cell" data-label="Role">
                <RoleChip admin={u.role === "admin"} />
                {mayViewAs(user, u, readOnly) ? (
                  <>
                    {" "}
                    <button
                      type="button"
                      className="set-secondary set-users-viewas"
                      data-view-as={u.username}
                      onClick={(event) => {
                        // The row opens the member page; this button reloads as the member instead.
                        event.stopPropagation();
                        if (!startViewAs(user, { username: u.username, name: u.name || u.username })) {
                          window.dispatchEvent(new CustomEvent(TOAST_EVENT, {
                            detail: { text: "Member view could not start. Try again.", tone: "error" },
                          }));
                        }
                      }}
                    >
                      View as member
                    </button>
                  </>
                ) : null}
              </td>
              <td role="cell" data-label="Access summary">
                    {u.role === "admin"
                      ? "Everything (admin)"
                      : (u.accessSummary ?? moduleWords(u.modules))}
              </td>
                {/* ⚠ A SPAN, NOT A BUTTON, AND THAT IS THE POINT OF R7. It is
                    inside the card's own button, so clicking the word "Edit"
                    opens exactly the page clicking anywhere else on the card
                    opens β€” which is the ruling, literally. A real nested button
                    is invalid markup, and the stretched-link alternative would
                    put two tab stops on one destination: the confusion the
                    ruling names, rebuilt in the accessibility tree. */}
              <td role="cell" data-label="Last active">{memberActivity(u)}</td>
            </tr>
          ))}
          </tbody>
        </table>
        </div>
      )}
    </div>
  );
}

function memberActivity(user: AdminUser) {
  const stamp = (user as AdminUser & { last_active?: string | null }).last_active;
  const date = stamp ? new Date(stamp) : null;
  return date && Number.isFinite(date.getTime())
    ? <time dateTime={stamp!}>{date.toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit" })}</time>
    : "Unavailable";
}

// β›” `BuPicker` WAS HERE, AND IT IS NOT COMING BACK (wave 15, R1). Business unit
// died as a USER-FACING CONCEPT: BU access is now one permanent filter among
// others under the per-module permissioning engine β€” "dba is any of [Fisch,
// Both]" says exactly what the two checkboxes used to say, in the same grammar
// as every other restriction, and an admin who wants a different cut is no
// longer limited to the two cuts somebody hard-coded.
//
// The picker's old help text is worth keeping in one form, because the property
// it named still holds and is still the point: a member scoped to one unit sees
// no other unit's data anywhere. What changed is WHERE that is enforced β€” the
// permanent filter and its server-side wall (C-PERM), not a `bus` list.
//
// ⚠ `bus` still exists on the RECORD and in `AdminUser` during the strangler
// period (legacy Streamlit pages read it; S1's migration converts it once). What
// no longer exists is a UI that WRITES it β€” see EditUser/AddUser below, which
// deliberately stopped sending the field they can no longer edit.

// β›” `EditUser` WAS HERE. It is not deleted so much as RELOCATED β€” every control
// it held (display name, role, deactivate/reactivate, password reset with its
// signs-them-out-everywhere warning) now lives at the top of the user page in
// `PermsEditor`, which is the whole of R7: *"Edit and clicking a user name
// should just be the EXACT same opening of a full page"*. What genuinely died
// is the SHAPE β€” a card that appeared at the bottom of the accounts list, below
// the fold, describing a row somewhere above it. Two doors, two layouts and one
// of them scrolled instead of navigating.
//
// ⚠ The load-bearing note from this block MOVES WITH THE FORM and is restated
// there: the PATCH still carries no `bus` (R1). With the picker gone the form
// cannot edit that field, so sending it would be a client echoing back a value
// it only read β€” and once the migration converts `bus` into a permanent filter
// and clears the field, that echo would RESURRECT it.

function AddUser({
  disabled,
  onCreated,
  onError,
}: {
  /** True while viewing as a member: the server would refuse the write. */
  disabled: boolean;
  onCreated: (msg: string) => void;
  onError: (msg: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const [username, setUsername] = useState("");
  const [name, setName] = useState("");
  const [role, setRole] = useState("user");
  const [password, setPassword_] = useState("");
  const [busy, setBusy] = useState(false);
  const requestScope = useRef<AbortController | null>(null);
  useLayoutEffect(() => {
    const scope = new AbortController();
    requestScope.current = scope;
    const invalidate = () => scope.abort();
    window.addEventListener(UNAUTHORIZED_EVENT, invalidate);
    window.addEventListener("aios:signed-out", invalidate);
    return () => {
      scope.abort();
      window.removeEventListener(UNAUTHORIZED_EVENT, invalidate);
      window.removeEventListener("aios:signed-out", invalidate);
    };
  }, []);

  if (!open)
    return (
      <button type="button" className="set-primary set-add" disabled={disabled} onClick={() => setOpen(true)}>
        Add user
      </button>
    );

  const valid = username.trim().length > 0 && password.length > 0;
  return (
    <section className="set-card">
      <h4 className="set-h4">New account</h4>
      <div className="set-field">
        <label className="set-label" htmlFor="set-new-user">Username</label>
        <input
          id="set-new-user"
          className="set-input"
          value={username}
          autoComplete="off"
          /* ⭐ WAVE 37 Β· T04 (ruling R8) β€” 254, WHICH IS THE SERVER'S OWN CAP
             (`routes_admin._UNAME_MAX`) AND NOT A ROUND NUMBER. The ticket said to
             "raise" a `maxLength={80}`; this input never had one β€” that 80 is the
             CONNECTOR LABEL field far below. So nothing was truncating anything, and
             the reason to add a cap now is the opposite of the ticket's: with the
             server accepting a 254-character email, a person typing a longer one
             should meet the boundary in the field rather than as a 400 after saving. */
          maxLength={254}
          onChange={(e) => setUsername(e.target.value)}
        />
        {/* S1's Y4 amendment 1, surfaced as guidance rather than as a 409. */}
        <p className="set-help">
          A full email address works here, and is usually the better choice: it is the
          one thing a person already knows about themselves. A short name works too.
          Must be new. To change an existing account, edit it above, because re-creating
          one would revive sessions that were revoked.
        </p>
      </div>
      <div className="set-field">
        <label className="set-label" htmlFor="set-new-name">Display name</label>
        <input id="set-new-name" className="set-input" value={name} onChange={(e) => setName(e.target.value)} />
      </div>
      <div className="set-field">
        <label className="set-label" htmlFor="set-new-role">Role</label>
        <select id="set-new-role" className="pg-select" value={role} onChange={(e) => setRole(e.target.value)}>
          <option value="user">Member</option>
          <option value="admin">Admin</option>
        </select>
      </div>
      <div className="set-field">
        <label className="set-label" htmlFor="set-new-pw">Password</label>
        <input
          id="set-new-pw"
          className="set-input"
          type="password"
          value={password}
          autoComplete="new-password"
          onChange={(e) => setPassword_(e.target.value)}
        />
        {/* Said before the click, because a new account is created OPEN and is
            narrowed afterwards. That order is the server's (an absent `bus`
            defaults to every unit) and this wave does not change it β€” what the
            wave changes is that "afterwards" now leads somewhere: open the
            account and set its per-module access, filters and hidden fields. */}
        <p className="set-help">
          A new account starts with access to everything this deployment shows.
          Open it from the list afterwards to set what they may see.
        </p>
      </div>
      <div className="set-actions">
        <button
          type="button"
          className="set-primary"
          disabled={busy || !valid || disabled}
          onClick={() => {
            const request = requestScope.current?.signal;
            if (!request || request.aborted) return;
            setBusy(true);
            void createUser({
              // D-385: sent as typed. The server folds a slug and keeps an email's spelling.
              username: username.trim(),
              // ⭐ WAVE 37 Β· T04 (R8) β€” A DISPLAY NAME DEFAULTED FROM AN EMAIL TAKES THE
              // LOCAL PART, NOT THE WHOLE ADDRESS. `name` is what the account rail, the
              // monogram and every "shared by" line render. Before R8 a username was a
              // short slug and defaulting to it read fine; now that the username IS the
              // email, the same default would put `farhan@teamroyalimports.com` where a
              // person's name goes, in a monogram that would read "f". The admin can
              // still type anything they like β€” this only changes what is used when
              // they type nothing.
              name: name || username.trim().split("@")[0] || username.trim(),
              role,
              // ⚠ `bus` IS DELIBERATELY ABSENT (R1) β€” see the note where the
              // picker used to be. The route defaults an absent `bus` to "all",
              // so this is the same account it always created, minus a client
              // asserting a value it cannot edit.
              // ⚠ `"all"`, never `[]`. An empty list READS as unrestricted, so
              // sending one to mean "nothing" would grant everything.
              modules: "all",
              password,
            }).then((r) => {
              if (request.aborted) return;
              setBusy(false);
              if (r.ok) {
                onCreated(`Created ${username.trim()}.`);
                setOpen(false);
                setUsername("");
                setName("");
                setPassword_("");
              } else {
                onError(r.message);
              }
            });
          }}
        >
          <Busy busy={busy} idle="Create account" doing="Creating" />
        </button>
        <button type="button" className="set-secondary" onClick={() => setOpen(false)}>
          Cancel
        </button>
      </div>
    </section>
  );
}

// ------------------------------------------------------------------ profile photo (wave 14)

/** Downscale + centre-crop to a <=128px JPEG data URL. JPEG at this size lands ~5-10KB,
 *  comfortably under the server's 64KB decoded wall; the server re-validates regardless. */
async function fileToAvatarDataUrl(file: File): Promise<string | null> {
  const url = URL.createObjectURL(file);
  try {
    const img = new Image();
    await new Promise<void>((res, rej) => {
      img.onload = () => res();
      img.onerror = () => rej(new Error("unreadable image"));
      img.src = url;
    });
    if (!img.width || !img.height) return null;
    const side = Math.min(128, Math.max(img.width, img.height));
    const canvas = document.createElement("canvas");
    canvas.width = side;
    canvas.height = side;
    const ctx = canvas.getContext("2d");
    if (!ctx) return null;
    const s = Math.min(img.width, img.height);
    ctx.drawImage(img, (img.width - s) / 2, (img.height - s) / 2, s, s, 0, 0, side, side);
    return canvas.toDataURL("image/jpeg", 0.85);
  } catch {
    return null;
  } finally {
    URL.revokeObjectURL(url);
  }
}

/** The first letter of a name, the way both shells compute it.
 *  ⚠ Unicode letter/number, not `[a-z0-9]` β€” the app's `_account_css` uses
 *  Python's `str.isalnum()`, so an ASCII-only class here would give a non-Latin
 *  name an initial in one door and a blank circle in the other. */
function initialOf(name: string): string {
  return (name.match(/[\p{L}\p{N}]/u)?.[0] ?? "?").toUpperCase();
}

/**
 * ⚠ WAVE 17 (16b) β€” THE INLINE STYLES ARE GONE, AND SO IS THEIR JUSTIFICATION.
 * This block used to carry twelve declarations in a `style` object under the
 * note *"the `.set-*`/`.shell-*` stylesheet is another wave-14 session's file"*.
 * That was true then and is not true now β€” SHELL owns the `.set-*` region this
 * wave β€” and an inline `background: "var(--lp-blue-tint)"` is still a colour
 * decision living outside the stylesheet, which is the thing the file-wide
 * token rule exists to stop. Two sizes are needed (the identity header and an
 * accounts card), so there are two classes rather than a size prop threading a
 * number into CSS.
 */
function AvatarPreview({ user, large }: { user: SessionUser; large?: boolean }) {
  const cls = large ? "set-avatar set-avatar--lg" : "set-avatar";
  if (user.avatar) {
    return <img className={cls} src={user.avatar} alt="" aria-hidden="true" />;
  }
  return (
    <span className={cls} aria-hidden="true">
      {initialOf(user.name)}
    </span>
  );
}

/** The accounts list's monogram. A separate component because `AdminUser`
 *  carries no `avatar` β€” only the SIGNED-IN user's photo is on the wire β€” so
 *  offering a photo slot here would be a hole nothing can fill. */
function Monogram({ name }: { name: string }) {
  return (
    <span className="set-avatar" aria-hidden="true">
      {initialOf(name)}
    </span>
  );
}

/** The role, as a chip rather than a table cell (16b). Two roles, one of which
 *  bypasses every rule in the product β€” that is a property of the account, and a
 *  property belongs beside the name, not in a row of key/value pairs. */
function RoleChip({ admin }: { admin: boolean }) {
  return (
    <span className={admin ? "set-chip set-chip--admin" : "set-chip"}>
      {admin ? "Admin" : "Member"}
    </span>
  );
}

function ProfilePhotoBlock({
  user,
  admin,
  readOnly,
  onUser,
}: {
  user: SessionUser;
  admin: boolean;
  /** True while viewing as a member: the photo is the member's and the server refuses writes. */
  readOnly: boolean;
  onUser?: (u: SessionUser) => void;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [photoAction, setPhotoAction] = useState<"upload" | "remove">("upload");
  const fileRef = useRef<HTMLInputElement>(null);

  const upload = useCallback(
    async (file: File) => {
      setBusy(true);
      setError("");
      setPhotoAction("upload");
      const dataUrl = await fileToAvatarDataUrl(file);
      if (!dataUrl) {
        setBusy(false);
        setError("That file could not be read as an image.");
        return;
      }
      const r = await setAvatar(dataUrl);
      setBusy(false);
      if (r.ok) {
        const fresh = parseUserEnvelope(r.data);
        if (fresh) onUser?.(fresh);
      } else {
        setError(r.message);
      }
    },
    [onUser]
  );

  const remove = useCallback(async () => {
    setBusy(true);
    setError("");
    setPhotoAction("remove");
    const r = await clearAvatar();
    setBusy(false);
    if (r.ok) {
      const fresh = parseUserEnvelope(r.data);
      if (fresh) onUser?.(fresh);
    } else {
      setError(r.message);
    }
  }, [onUser]);

  // β›” THE HELP SENTENCE IS DELETED (wave 17, item 16b, owner's instruction:
  // "replace with layout, not copy"). It read "Shown on Assignee fields and your
  // account chip. Square images look best; large ones are scaled down
  // automatically." Every clause was work the interface should do rather than
  // explain: WHERE the photo appears is answered by showing it at the size and
  // shape it will be worn, beside the name it belongs to; SQUARE IS BEST and
  // LARGE ONES ARE SCALED are apologies for a centre-crop-and-downscale that
  // already happens without asking (`fileToAvatarDataUrl`) and that the user
  // cannot influence. A sentence describing behaviour the reader has no control
  // over is decoration.
  return (
    <div className="set-identity">
      <AvatarPreview user={user} large />
      <div className="set-identity-body">
        <div className="set-identity-head">
          <span className="set-identity-name">{user.name}</span>
          <RoleChip admin={admin} />
        </div>
        <div className="set-identity-sub">{user.username}</div>
        <div className="set-identity-acts">
          <input
            ref={fileRef}
            type="file"
            accept="image/png,image/jpeg"
            className="set-filepick"
            disabled={readOnly}
            onChange={(e) => {
              const f = e.target.files?.[0];
              e.target.value = "";
              if (f) void upload(f);
            }}
          />
          <button
            type="button"
            className="set-primary"
            disabled={busy || readOnly}
            onClick={() => fileRef.current?.click()}
          >
            <Busy busy={busy} idle={user.avatar ? "Change photo" : "Upload photo"} doing="Uploading" />
          </button>
          {user.avatar ? (
            <button type="button" className="set-secondary" disabled={busy || readOnly} onClick={remove}>
              Remove
            </button>
          ) : null}
        </div>
        {error ? <div className="set-error set-identity-err" role="alert">
          <span title={error}>Could not update your photo.</span>
          <button type="button" className="set-secondary" disabled={busy || readOnly}
            onClick={() => {
              if (photoAction === "remove") void remove();
              else fileRef.current?.click();
            }}>Retry</button>
        </div> : null}
      </div>
    </div>
  );
}

// ------------------------------------------------------------------ the modal

export function SettingsModal({
  user,
  section,
  onSection,
  onClose,
  onUser,
  moduleLabels,
}: {
  user: SessionUser;
  section: SettingsSection;
  onSection: (s: SettingsSection) => void;
  onClose: () => void;
  /** Wave 14 C-AVATAR β€” the shell's session setter, so a photo change updates the account
   *  chip live instead of on the next full reload. Optional: absent, the photo still saves. */
  onUser?: (u: SessionUser) => void;
  /** Registry key β†’ the label the nav already shows for it. Passed down rather
   *  than fetched or hardcoded: the shell holds a server-filtered nav with every
   *  label in it, and a second copy of that mapping in this file would be a
   *  place for "Customer" to become "Customers" in one door only. Absent β‡’ rows
   *  fall back to the key, which is honest if ugly. */
  moduleLabels?: Record<string, string>;
}) {
  const [settings, setSettings] = useState<SettingsPayload | null>(null);
  const [settingsLoading, setSettingsLoading] = useState(true);
  const [settingsError, setSettingsError] = useState("");
  const panelRef = useRef<HTMLDivElement>(null);
  useOverlayLayer({
    panelRef,
    onDismiss: onClose,
    dismissOnOutside: false,
    trapFocus: true,
  });
  const admin = isAdmin(user);
  // S85-T157: fixed for the page's life, because entering or leaving the member view reloads.
  const readOnly = viewAsActive();
  useEffect(() => {
    const route = retiredSettingsRoute(section);
    if (!route) return;
    onClose();
    window.location.hash = route;
  }, [section, onClose]);
  // Wave 19 (C2) β€” `=== true`, not truthy: absent or malformed reads as NO.
  const platformAdmin = settings?.platformAdmin === true;

  const reloadSettings = useCallback(() => {
    setSettingsLoading(true);
    setSettingsError("");
    void getSettings().then((r) => {
      if (r.ok) setSettings(r.data);
      else setSettingsError(r.message);
      setSettingsLoading(false);
    });
  }, []);
  useEffect(reloadSettings, [reloadSettings]);

  // WAVE 19 R13 β€” the tuple grew a third member: the tab's mark. ONE data change
  // and one line in the render loop below, which is the whole of the ruling.
  const rail: Array<[SettingsSection, string, ReactNode]> = [
    ["account", "Account", IconAccount],
    ["scope", "Your access", IconAccess],
    ["security", "Security", IconSecurity],
    // ⭐⭐ WAVE 52 Β· T19 (owner instruction 21) β€” NOT admin-gated, on the same footing as
    // `account` and `scope` immediately above: every user manages their own shortcut
    // preferences, and there is nothing behind this room a member's account cannot already do to
    // itself (the store is client-local, keyed to nothing server-side).
    ["shortcuts", "Sheet shortcuts", IconShortcuts],
    ["notifications", "Notifications", IconNotifications],
    ["activity", "Activity log", IconActivity],
    ...(admin
      ? ([
          ["usage", "Usage", IconUsage],
          ["brand", "Brand", IconBrand],
          ["users", "Manage users", IconUsers],
          // R31 places field controls on each database, in Connectors or Data.
          // ⭐ WAVE 33, owner item 10 β€” placed by the owner, verbatim: *"under a
          // module called 'Manage agent' which should be under 'Manage user'"*.
          // Immediately after `users`, so "under" is literal in the rail rather
          // than a tab hidden inside the other room.
          // ⭐ WAVE 47, owner instruction 6 β€” RELABELLED, verbatim: *"Let's change
          // the naming of Manage agent under setting to Manage slack"*. The wave-33
          // wording above is left as written because it is the owner's original
          // quotation. Only the rendered LABEL moved; the tab id stays `agents`,
          // which `routes_slack.py`, `permsModel.ts` and every deep link name.
          // Wave 18 (C7): the tenant's credential store + data-source status board.
          /* β›”β›” THE `Statements` ROW IS GONE (wave 35 Β· T38, owner item 14 / ruling R10).
             It is an AGENT now β€” `Agents -> Monthly statements` β€” where a scheduled run assembles
             a batch and parks it, and a person releases it with a click.
             ⚠ The send DOOR is unchanged and unweakened: `routes_statements`, `admin_gate` +
             the Royal-Imports gate, `collections_send.queue_statement` with SAFE_MODE in the data
             layer. One of its two front doors closed; the capability did not move.
             ⚠ A stored preference naming the old section lands on Account, not on a blank pane β€”
             `permsModel.RETIRED_SECTIONS`. */
        ] as Array<[SettingsSection, string, ReactNode]>)
      : []),
    // Wave 19 (R3 / C2): the Loopable admin plane. Gated on the SERVER's
    // `platformAdmin`, never on `admin` β€” R3 is explicit that a tenant-scoped
    // admin does not qualify, so this entry appears for exactly one account and
    // is invisible to every tenant admin in the product.
    ...(platformAdmin
      ? ([["padmin", "Loopable admin", IconTenants]] as Array<
          [SettingsSection, string, ReactNode]
        >)
      : []),
  ];
  // A non-admin deep-linked to the users pane lands on Account rather than on
  // an empty frame. The server would refuse the data anyway; this just avoids
  // showing a room with nothing in it. The rule is a NAMED function so the gate
  // can negative-control it β€” see `permsModel.reachableSection`.
  //
  // β›” `padmin` IS GATED HERE, NOT IN THAT FUNCTION, and the reason is that its
  // input does not exist there. `reachableSection` takes `admin` β€” a boolean off
  // the user record β€” while `platformAdmin` arrives asynchronously on the
  // settings payload and (per R3) is NOT implied by tenant admin. Passing it
  // through `reachableSection` would have meant either widening that function's
  // signature and re-aiming a negative control that guards a different rule, or
  // conflating the two admin concepts the ruling exists to keep apart. Composed
  // instead: the section falls back to Account until the server has said yes.
  const active =
    section === "padmin" && !platformAdmin ? "account" : reachableSection(section, admin);

  return (
    <div className="set-backdrop">
      {/* ⚠ WAVE 19 R12 β€” the modal is "Settings", and the ACCESSIBLE name tracks
          the visible one, which is the half that is easy to forget. A dialog a
          screen reader announces as "Profile" while the rail reads "Settings" is
          the same drift as a stale comment, only harder to notice: nobody
          looking at the screen can see it. Manage users is still a SECTION
          inside it (R12 is a rename, not a re-architecture). */}
      <div className="set-modal" ref={panelRef} role="dialog" aria-modal="true" aria-label="Settings">
        <nav className="set-rail">
          <span className="set-rail-cap">Settings</span>
          {rail.map(([key, label, icon]) => (
            <button
              key={key}
              data-section={key}
              type="button"
              className={"set-rail-item" + (active === key ? " is-active" : "")}
              onClick={() => onSection(key)}
            >
              {icon}
              {label}
            </button>
          ))}
        </nav>

        <div className="set-body">
          <button type="button" className="set-close" onClick={onClose} aria-label="Close settings">
            Γ—
          </button>
          {settingsError ? <div className="set-error" role="alert">
            <span title={settingsError}>Could not read your settings.</span>
            <button type="button" className="set-secondary" onClick={reloadSettings}>Retry</button>
          </div> : null}

          {/* Wave 33 (owner item 10), wired the way contract C2's lesson demands
              a new surface be wired: at the MOUNT SITE, not by an import that a
              grep would mistake for a render. The pane is self-contained β€” it
              fetches its own data and owns its loading/empty/error states β€” and
              `reachableSection` has already bounced a non-admin to Account. */}
          {/* Wave 52 Β· T19 β€” self-contained, like its neighbours: it reads and writes
              `sheet/shortcuts.ts`'s own localStorage store directly and needs nothing passed
              in, because a keyboard preference is not server data. */}
          {/* S85-T157: while viewing as a member, each pane that writes to the server sits behind
              one fence. Sheet shortcuts write only this browser's own preference store, and the
              Activity log keeps its filters, because reading is what the view is for. */}
          {active === "shortcuts" ? <ShortcutSettings /> : null}
          {active === "notifications" ? (
            <ReadOnlyFence readOnly={readOnly}><NotifyDestinations onConnect={onClose} /></ReadOnlyFence>
          ) : null}
          {active === "security" ? <ReadOnlyFence readOnly={readOnly}><SecurityPane /></ReadOnlyFence> : null}
          {active === "activity" ? <ActivityLogPage user={user} /> : null}
          {active === "usage" ? <ReadOnlyFence readOnly={readOnly}><UsagePane user={user} /></ReadOnlyFence> : null}
          {active === "brand" ? <ReadOnlyFence readOnly={readOnly}><BrandPane /></ReadOnlyFence> : null}
          {/* Wave 19 contract C2 β€” the wiring record, verified at the MOUNT SITE
              (the wave-14 lesson: an occurrence-grep proves an import, not a
              render): `settings/AdminPane.tsx β†’ SettingsModal.tsx pane switch β†’
              prop user`. The pane is session D's, self-contained: it fetches its
              own data and owns its loading/empty/error states, so mounting it
              cannot fail on plumbing. Its prop is typed STRUCTURALLY on D's side
              ({username; name; role}), so the shell's `SessionUser` satisfies it
              by structural typing β€” no cast here, and no import from `shell/`
              there. `active` cannot be "padmin" unless the server said so. */}
          {active === "padmin" ? (
            <>
              <AdminPane user={user} />
              <OperatorPage platformAdmin={platformAdmin} />
            </>
          ) : null}

          {active === "account" ? (
            <div className="set-pane">
              <h3 className="set-h">Account</h3>
              {/* ⚠ WAVE 17 (16b) β€” THE THREE KEY/VALUE ROWS ARE NOT DELETED,
                  THEY ARE LAID OUT. "Signed in as", "Username" and "Role" were a
                  three-row table restating what a photo, a name and a chip say
                  at a glance β€” and the photo block sat UNDER them, so the pane
                  opened on a label reading "Signed in as" above the picture of
                  the person it was labelling. The identity header carries all
                  three now: the name at title weight, the username beneath it,
                  the role as a chip beside it. Nothing was dropped; the labels
                  were, because each one named the obvious. */}
              <ProfilePhotoBlock user={user} admin={admin} readOnly={readOnly} onUser={onUser} />
            </div>
          ) : null}

          {active === "scope" ? (
            <div className="set-pane">
              <h3 className="set-h">Your access</h3>
              {/* β›” THE "Business units" ROW IS GONE (R1) β€” the concept it
                  reported no longer exists on this side of the product. It is
                  NOT replaced by nothing: what shapes a restricted account's
                  rows is now a permanent filter per module, and the rows below
                  say so. A pane reporting "All modules" while a filter quietly
                  halves somebody's book is worse than the row it replaced β€”
                  that is the user who files a bug about the numbers. */}
              <p className="set-help set-pane-intro">
                What this account may open, and anything that narrows it. Only an
                administrator can change this.
              </p>
              {/* 16b β€” one card, so the restrictions read as a group belonging to
                  the heading rather than as loose rows floating under it. */}
              {settingsLoading ? <div className="set-skeleton" role="status" aria-label="Loading access" aria-busy="true">
                <span className="set-skeleton-line" aria-hidden="true" />
                <span className="set-skeleton-line" aria-hidden="true" />
                <span className="set-skeleton-line" aria-hidden="true" />
              </div> : settingsError ? null : <section className="set-card set-card--rows">
                <div className="pg-drill-row">
                  <span className="pg-drill-key">Modules</span>
                  <span className="pg-drill-val">
                    {moduleWords(settings?.scope.modules ?? user.modules)}
                  </span>
                </div>
                {/* An admin's "All modules" is true but does not say WHY, and the
                    why is the part that matters: it is not a grant somebody can
                    revoke module by module, it is a bypass. The accounts list
                    already says "Everything (admin)" β€” this is the same fact, on
                    the account's own page, so the two doors agree. */}
                {admin ? (
                  <div className="pg-drill-row">
                    <span className="pg-drill-key">Restrictions</span>
                    <span className="pg-drill-val">
                      None apply. Administrators bypass every rule
                    </span>
                  </div>
                ) : null}
              {/* One row per module the account is restricted in. `moduleSummary`
                  is the SAME sentence the admin editor shows, from the same
                  function β€” two dialects of "2 conditions, 3 fields hidden"
                  would eventually disagree about what a rule says. Admins are
                  skipped: they bypass perms entirely, so any stored rule is
                  inert and printing it here would be a lie about their access. */}
              {!admin
                ? Object.entries(settings?.scope.perms ?? {}).map(([key, raw]) => {
                    const entry = parseEntry(raw);
                    const words = moduleSummary(entry);
                    // "Full access" adds nothing beside the Modules row above;
                    // only a REAL narrowing earns a line.
                    if (words === "Full access") return null;
                    return (
                      <div className="pg-drill-row" key={key}>
                        <span className="pg-drill-key">{moduleLabels?.[key] ?? key}</span>
                        <span className="pg-drill-val">{words}</span>
                      </div>
                    );
                  })
                : null}
              </section>}
            </div>
          ) : null}

          {active === "users" ? <UsersPane user={user} readOnly={readOnly} /> : null}
        </div>
      </div>
    </div>
  );
}