File size: 49,767 Bytes
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
3331871
 
 
 
 
 
 
affe37f
 
8145bee
 
3331871
 
 
 
 
 
 
 
8145bee
 
3331871
 
 
 
 
 
 
 
 
8145bee
 
 
3331871
 
 
 
 
 
 
 
 
 
 
9a6cb9a
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
c72f0a1
3331871
 
 
 
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
9a6cb9a
 
 
 
 
 
 
 
 
 
c72f0a1
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
9a6cb9a
 
 
 
 
c72f0a1
 
9a6cb9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
affe37f
8145bee
 
 
 
 
 
 
 
 
 
affe37f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8145bee
 
affe37f
 
 
8145bee
 
 
affe37f
8145bee
 
 
 
affe37f
8145bee
 
 
 
 
 
 
 
 
 
affe37f
 
 
8145bee
 
 
 
 
 
 
affe37f
 
 
 
 
8145bee
 
 
affe37f
 
 
 
 
8145bee
affe37f
 
 
 
8145bee
 
 
 
 
 
 
c72f0a1
8145bee
affe37f
c72f0a1
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
8145bee
 
 
 
 
 
 
c72f0a1
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
3331871
 
 
c72f0a1
3331871
c72f0a1
3331871
 
 
 
c72f0a1
3331871
 
 
 
 
c72f0a1
3331871
9a6cb9a
 
 
 
3331871
 
c72f0a1
 
3331871
c72f0a1
 
 
 
 
 
 
 
3331871
c72f0a1
3331871
 
 
 
 
 
 
c72f0a1
3331871
 
 
c72f0a1
3331871
9a6cb9a
 
 
 
 
 
 
 
3331871
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
 
 
 
 
 
 
3331871
affe37f
8145bee
c72f0a1
3331871
c72f0a1
3331871
 
 
 
 
 
0427303
 
9a6cb9a
0427303
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
c72f0a1
 
3331871
 
 
 
 
 
 
 
 
 
c72f0a1
 
 
 
3331871
 
 
 
 
 
 
81a8217
0427303
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
c72f0a1
 
3331871
 
 
 
c72f0a1
 
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c72f0a1
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a6cb9a
3331871
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// ---------------------------------------------------------------------------
// settings / AdminPane.tsx β€” THE LOOPABLE ADMIN PLANE (wave 19, owner item 13 /
// R3+R4, contract C2).
//
// The one surface in this product that looks ACROSS tenants: who our customers
// are, how many people use each workspace, what they have built in it, whether
// their data sources are alive, and what the automation fleet costs.
//
// SELF-CONTAINED BY CONTRACT (C2). It fetches its own data via
// `platformAdminApi` and takes ONE prop, so mounting it is a rail entry plus a
// line in the pane switch β€” `SettingsModal.tsx` is another session's file this
// wave and must not have to learn anything about this pane's data.
//
// ⚠ THE PROP IS TYPED STRUCTURALLY, not as `SessionUser` from `../shell/session`.
// The mount site passes the shell's session user (a wider object), which
// satisfies this shape by structural typing β€” and this pane therefore imports
// nothing from the shell, which is what the wave's cross-fence rule asks for
// while `session.ts` is open on another desk.
//
// β›” EVERY NUMBER HERE IS THE SERVER'S, AND EVERY NUMBER DRILLS. Clicking a count
// opens the rows it was computed from β€” the same collector, projected twice
// ([[no-unverifiable-aggregates]]). A count that could not be READ renders as an
// its cause, never as a zero: "this customer has no databases" and
// "we could not look" are different facts and the pane refuses to conflate them.
//
// DESIGN: sentence-case micro-labels (R6 β€” no caps in app chrome), short noun
// headers, tabular figures right-aligned, hairlines not shadows, tokens only,
// no emojis (DESIGN.md Β§2–§4).
// ---------------------------------------------------------------------------

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS, TOAST_EVENT, UNAUTHORIZED_EVENT } from "../apiContract";
import { useEscapeClose } from "../ui/useEscapeClose";
import "../signup/signup.css";
import type {
  AutomationRow,
  ConnectorRow,
  DatabaseRow,
  FleetCost,
  Overview,
  PlatformUser,
  ReleasesPayload,
  SignupRequest,
  TenantRow,
} from "./platformAdminApi";
import {
  getAutomations,
  getAws,
  getReleases,
  getConnectors,
  getDatabases,
  getOverview,
  getUsers,
  getSignupRequests,
  approveSignupRequest,
  declineSignupRequest,
} from "./platformAdminApi";

// --- formatting -------------------------------------------------------------

const int = (n: number) => n.toLocaleString();

/** A count that may be unknown. `null` is NOT zero β€” see the api module's header. */
function Count({ n, why }: { n: number | null | undefined; why?: string }) {
  if (n === null || n === undefined)
    return (
      <span className="padmin-unknown" title={why || "This could not be read just now"}>
        Unknown
      </span>
    );
  return <>{int(n)}</>;
}

/** "3 days ago" for a stamp, "never" for an absent one. Never a fabricated date.
 *
 *  β›” ONLY FOR OFFSET-BEARING STAMPS. `Date.parse` reads a stamp with no zone as
 *  BROWSER-LOCAL, so running a container-local timestamp through this reports the
 *  viewer's UTC offset as elapsed time β€” hours of error in a column people scan,
 *  and a future-dated stamp that renders as "just now" indefinitely. Everything
 *  this pane passes here (`last_login`, `last_active`, `generatedAt`) is written
 *  with an explicit offset; the automation engine's `lastRunAt` is NOT, so it is
 *  rendered verbatim instead. */
function ago(stamp: string): string {
  if (!stamp) return "never";
  const t = Date.parse(stamp.includes("T") ? stamp : stamp.replace(" ", "T"));
  if (Number.isNaN(t)) return stamp;
  const mins = Math.floor((Date.now() - t) / 60000);
  if (mins < 2) return "just now";
  if (mins < 60) return `${mins} minutes ago`;
  const hours = Math.floor(mins / 60);
  if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
  const days = Math.floor(hours / 24);
  if (days < 60) return `${days} day${days === 1 ? "" : "s"} ago`;
  return `${Math.floor(days / 30)} months ago`;
}

type DrillKind = "users" | "databases" | "connectors" | "automations";

const DRILL_NOUN: Record<DrillKind, string> = {
  users: "People",
  databases: "Databases",
  connectors: "Data sources",
  automations: "Automations",
};

/** The loading shape β€” a skeleton, not a spinner (DESIGN.md Β§4). */
function Skeleton({ rows = 3 }: { rows?: number }) {
  return (
    <div className="padmin-skel set-skeleton" role="status" aria-label="Loading admin data" aria-busy="true">
      {Array.from({ length: rows }, (_, i) => (
        <div key={i} className="padmin-skel-row set-skeleton-line" aria-hidden="true" />
      ))}
    </div>
  );
}

type NeonMetric = "transfer_gb" | "compute_hours" | "storage_gib";
type NeonNumbers = Record<NeonMetric, number | null>;
interface NeonUsage {
  available: boolean;
  cause: string | null;
  read_at: string;
  period: { start: string; end: string };
  usage: NeonNumbers;
  allowance: Record<NeonMetric, number>;
  share: NeonNumbers;
  rate: Record<NeonMetric, { per_day: number | null; cause: string | null }>;
  projection: {
    transfer: number | null; compute: number | null; storage: number | null;
    total: number | null; currency: string; cause: string | null;
    basis: Record<NeonMetric, string>;
  };
  samples: { at: string; transfer_bytes: number; compute_seconds: number; storage_bytes: number; period_start: string }[];
  sampler: { every_s: number; last_at: string | null; pending: number; persisted: string | null; cause: string | null };
  alarm: { level: "red"; message: string; test: boolean } | null;
  guards: { ok: boolean; message: string } | null;
}

async function getNeon(): Promise<{ ok: true; data: NeonUsage } | { ok: false; message: string }> {
  try {
    const response = await fetch(`${API_V1}/platform-admin/neon`, { credentials: CREDENTIALS });
    if (!response.ok) {
      return { ok: false, message: response.status === 403
        ? "Neon usage is only available to platform operators."
        : response.status === 401 ? "Sign in to read Neon usage."
        : `Neon usage could not be loaded (HTTP ${response.status}).` };
    }
    const data = await response.json() as NeonUsage;
    if (typeof data?.available !== "boolean")
      return { ok: false, message: "The Neon usage response could not be read." };
    return { ok: true, data };
  } catch {
    return { ok: false, message: "The Neon usage service could not be reached or its response could not be read." };
  }
}

const neonNumber = (value: number) => value.toLocaleString(undefined, { maximumFractionDigits: 2 });
const neonDate = (value: string) => new Date(value).toLocaleDateString(undefined,
  { year: "numeric", month: "short", day: "numeric", timeZone: "UTC" });
const neonTime = (value: string) => new Date(value).toLocaleString(undefined,
  { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZone: "UTC" });
const neonMoney = (value: number) => value.toLocaleString(undefined,
  { style: "currency", currency: "USD" });

function NeonCard({ data, error, onRetry }: { data: NeonUsage | null; error: string; onRetry: () => void }) {
  const metrics: { key: NeonMetric; label: string; unit: string }[] = [
    { key: "transfer_gb", label: "Transfer", unit: "GB" },
    { key: "compute_hours", label: "Compute", unit: "CU-hours" },
    { key: "storage_gib", label: "Storage", unit: "GiB" },
  ];
  const cause = error || (data && !data.available ? data.cause || "Neon usage could not be read." : "");
  return (
    <section className="padmin-block" aria-label="Neon usage"
      style={data?.alarm && !cause ? { border: "1px solid var(--lp-red-deep)", padding: 12 } : undefined}>
      <h4 className="padmin-h4">Neon</h4>
      {cause ? <div className="set-error" role="alert"><span title={cause}>Could not read Neon usage.</span>
        <button type="button" className="set-secondary" onClick={onRetry}>Retry</button></div> : !data ? <Skeleton rows={2} /> : (
        <>
          {data.alarm ? (
            <p className="set-help" role="status" style={{ color: "var(--lp-red-deep)",
              background: "var(--lp-red-tint)", padding: 8, fontVariantNumeric: "tabular-nums" }}>
              {data.alarm.test && !data.alarm.message.startsWith("TEST ") ? "TEST " : ""}{data.alarm.message}
            </p>
          ) : null}
          <p className="set-help">
            {neonDate(data.period.start)} to {neonDate(data.period.end)} (UTC, end exclusive).
            {" "}Project totals include staging and production. Read {neonTime(data.read_at)} UTC.
          </p>
          <div className="padmin-totals">
            {metrics.map(({ key, label, unit }) => (
              <div className="padmin-total" key={key}>
                <span className="padmin-total-label">{label}</span>
                <span className="padmin-total-value" style={{ fontVariantNumeric: "tabular-nums" }}>
                  {data.usage[key] === null ? "This total could not be read" : `${neonNumber(data.usage[key])} ${unit}`}
                </span>
                <span className="set-help">
                  of {neonNumber(data.allowance[key])} {unit}
                  {data.share[key] === null ? "; usage share could not be read" : ` Β· ${neonNumber(data.share[key] * 100)}% used`}
                </span>
              </div>
            ))}
          </div>
          <p className="set-help" style={{ fontVariantNumeric: "tabular-nums" }}>
            GB per day: {data.rate.transfer_gb.per_day === null
              ? data.rate.transfer_gb.cause
              : neonNumber(data.rate.transfer_gb.per_day)}
          </p>
          <p className="set-help" style={{ fontVariantNumeric: "tabular-nums" }}>
            Projected bill: {data.projection.total === null
              ? data.projection.cause
              : `${neonMoney(data.projection.total)} at period end`}
          </p>
          {data.projection.total !== null ? (
            <>
              <p className="set-help">
                {metrics.map(({ key, label }) => `${label}: ${data.projection.basis[key]}`).join(". ")}.
              </p>
              <p className="set-help" style={{ fontVariantNumeric: "tabular-nums" }}>
                Transfer {neonMoney(data.projection.transfer!)} Β· Compute {neonMoney(data.projection.compute!)}
                {" "}Β· Storage {neonMoney(data.projection.storage!)}. Compute is billed from the first CU-hour.
              </p>
            </>
          ) : null}
          <h5 className="padmin-h4">Sample history</h5>
          {data.samples.length ? (
            <div className="padmin-tablewrap" style={{ maxHeight: "18rem", overflow: "auto" }}>
              <table className="padmin-table" style={{ fontVariantNumeric: "tabular-nums" }}>
                <thead><tr>
                  <th>Time (UTC)</th>
                  <th className="padmin-num">Transfer (GB)</th>
                  <th className="padmin-num">Compute (CU-hours)</th>
                  <th className="padmin-num">Storage (GiB)</th>
                </tr></thead>
                <tbody>{[...data.samples].reverse().map((sample) => (
                  <tr key={`${sample.period_start}/${sample.at}`}>
                    <td title={`Billing period starts ${neonDate(sample.period_start)}`}>{neonTime(sample.at)}</td>
                    <td className="padmin-num">{neonNumber(sample.transfer_bytes / 1e9)}</td>
                    <td className="padmin-num">{neonNumber(sample.compute_seconds / 3600)}</td>
                    <td className="padmin-num">{neonNumber(sample.storage_bytes / 2 ** 30)}</td>
                  </tr>
                ))}</tbody>
              </table>
            </div>
          ) : <p className="set-help">No sample history is available yet.</p>}
          <p className="set-help">
            {data.sampler.every_s > 0 ? `Sampled every ${neonNumber(data.sampler.every_s / 3600)} hours. ` : ""}
            {data.sampler.persisted ? `History saved ${neonTime(data.sampler.persisted)} UTC. ` : ""}
            {data.sampler.pending > 0 ? `${data.sampler.pending} samples awaiting storage. ` : ""}
            {data.sampler.cause}
          </p>
        </>
      )}
      {data?.guards ? (
        <p className="set-help" role="status" style={{ fontVariantNumeric: "tabular-nums",
          color: data.guards.ok ? undefined : "var(--lp-red-deep)" }}>
          {data.guards.message}
        </p>
      ) : null}
    </section>
  );
}

interface DigitalOceanUsage {
  available: boolean;
  cause: string | null;
  read_at: string;
  cluster: {
    available: boolean; cause: string | null; source: string; read_at: string;
    name: string | null; size: string | null; num_nodes: number | null;
    region: string | null; status: string | null;
  };
  fixed_price: { monthly_usd: number | null; source: string | null; read_at: string; cause: string | null };
  balance: {
    available: boolean; cause: string | null; source: string; read_at: string;
    month_to_date_usage: number | null; account_balance: number | null;
    month_to_date_balance: number | null; generated_at: string | null;
  };
  billing: { available: boolean; cause: string | null; source: string; read_at: string; has_more?: boolean };
  billing_history: { date: string; description: string; amount: number; type: string }[];
  sampler: { every_s: number; last_at: string | null; persisted: string | null; cause: string | null };
  alarm: { level: "red"; message: string; test: boolean } | null;
  alarm_cause: string | null;
}

async function getDigitalOcean(): Promise<{ ok: true; data: DigitalOceanUsage } | { ok: false; message: string }> {
  try {
    const response = await fetch(`${API_V1}/platform-admin/do`, { credentials: CREDENTIALS });
    if (!response.ok) {
      return { ok: false, message: response.status === 403
        ? "DigitalOcean usage is only available to platform operators."
        : response.status === 401 ? "Sign in to read DigitalOcean usage."
        : `DigitalOcean usage could not be loaded (HTTP ${response.status}).` };
    }
    const data = await response.json() as DigitalOceanUsage;
    if (typeof data?.available !== "boolean" || !data.cluster || !data.balance
        || !data.fixed_price || !data.billing || !Array.isArray(data.billing_history) || !data.sampler)
      return { ok: false, message: "The DigitalOcean usage response could not be read." };
    return { ok: true, data };
  } catch {
    return { ok: false, message: "The DigitalOcean usage service could not be reached or its response could not be read." };
  }
}

// Provider labels are also screen copy. Preserve their meaning using words for ranges.
const doText = (value: string) => value.replace(/\u2014/g, "; ").replace(/\u2013/g, " to ");
const doTime = (value: string) => `${new Date(value).toLocaleString(undefined,
  { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", timeZone: "UTC" })} UTC`;

function DigitalOceanCard({ data, error, onRetry }: { data: DigitalOceanUsage | null; error: string; onRetry: () => void }) {
  const cause = error || (data && !data.available ? data.cause || "DigitalOcean usage could not be read." : "");
  return (
    <section className="padmin-block" aria-label="DigitalOcean usage"
      style={data?.alarm && !cause ? { border: "1px solid var(--lp-red-deep)", padding: 12 } : undefined}>
      <h4 className="padmin-h4">DigitalOcean</h4>
      {cause ? <div className="set-error" role="alert"><span title={doText(cause)}>Could not read DigitalOcean usage.</span>
        <button type="button" className="set-secondary" onClick={onRetry}>Retry</button></div> : !data ? <Skeleton rows={2} /> : (
        <>
          {data.alarm ? (
            <p className="set-help" role="status" style={{ color: "var(--lp-red-deep)",
              background: "var(--lp-red-tint)", padding: 8, fontVariantNumeric: "tabular-nums" }}>
              {data.alarm.test && !data.alarm.message.startsWith("TEST ") ? "TEST " : ""}{doText(data.alarm.message)}
            </p>
          ) : null}
          {data.cluster.available ? (
            <p className="set-help">
              {doText(data.cluster.name!)} Β· {doText(data.cluster.size!)} Β· {data.cluster.num_nodes}
              {data.cluster.num_nodes === 1 ? " node" : " nodes"} Β· {doText(data.cluster.region!)} Β· {doText(data.cluster.status!)}
            </p>
          ) : <p className="set-help">Cluster: {doText(data.cluster.cause || "The cluster could not be read.")}</p>}
          <div className="padmin-totals">
            <div className="padmin-total">
              <span className="padmin-total-label">Fixed price</span>
              <span className="padmin-total-value" style={{ fontVariantNumeric: "tabular-nums" }}>
                {data.fixed_price.monthly_usd === null ? "Unknown" : `${neonMoney(data.fixed_price.monthly_usd)} a month`}
              </span>
              <span className="set-help">
                {data.fixed_price.monthly_usd === null
                  ? doText(data.fixed_price.cause || "The fixed price could not be read.")
                  : `${doText(data.fixed_price.source!)}. Read ${doTime(data.fixed_price.read_at)}.`}
              </span>
            </div>
            <div className="padmin-total">
              <span className="padmin-total-label">Month to date</span>
              <span className="padmin-total-value" style={{ fontVariantNumeric: "tabular-nums" }}>
                {!data.balance.available || data.balance.month_to_date_usage === null
                  ? "This total could not be read" : neonMoney(data.balance.month_to_date_usage)}
              </span>
              <span className="set-help">
                {data.balance.available && data.balance.generated_at
                  ? `As of ${doTime(data.balance.generated_at)}.`
                  : doText(data.balance.cause || "The balance snapshot could not be read.")}
              </span>
            </div>
          </div>
          {data.balance.available ? (
            <p className="set-help">{doText(data.balance.source)}. Read {doTime(data.balance.read_at)}.</p>
          ) : null}
          <h5 className="padmin-h4">Billing history</h5>
          {!data.billing.available ? (
            <p className="set-help">{doText(data.billing.cause || "Billing history could not be read.")}</p>
          ) : (
            <>
              {data.billing_history.length ? (
                <div className="padmin-tablewrap" style={{ maxHeight: "18rem", overflow: "auto" }}>
                  <table className="padmin-table" style={{ fontVariantNumeric: "tabular-nums" }}>
                    <thead><tr><th>Date (UTC)</th><th>Description</th><th className="padmin-num">Amount</th></tr></thead>
                    <tbody>{data.billing_history.map((row, index) => (
                      <tr key={`${row.date}/${index}`}>
                        <td>{neonDate(row.date)}</td><td>{doText(row.description)}</td>
                        <td className="padmin-num">{neonMoney(row.amount)}</td>
                      </tr>
                    ))}</tbody>
                  </table>
                </div>
              ) : <p className="set-help">No billing history yet</p>}
              <p className="set-help">
                {doText(data.billing.source)}. Read {doTime(data.billing.read_at)}.
                {data.billing.has_more ? " Showing the latest page." : ""}
              </p>
            </>
          )}
          {data.alarm_cause ? <p className="set-help">{doText(data.alarm_cause)}</p> : null}
          <p className="set-help">
            {data.sampler.every_s > 0 ? `Sampled every ${neonNumber(data.sampler.every_s / 3600)} hours. ` : ""}
            {data.sampler.persisted ? `History saved ${doTime(data.sampler.persisted)}. ` : ""}
            {doText(data.sampler.cause || "")}
          </p>
        </>
      )}
    </section>
  );
}

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

function SignupRequests({ tenants, owner }: { tenants: TenantRow[]; owner: string }) {
  const [requests, setRequests] = useState<SignupRequest[] | null>(null);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [approving, setApproving] = useState<string | null>(null);
  const [tenant, setTenant] = useState("");
  const [busy, setBusy] = useState(false);
  const acting = useRef(false);
  const opener = useRef<HTMLButtonElement | null>(null);
  const picker = useRef<HTMLSelectElement | null>(null);
  const companies = tenants.filter((company) => company.status === "active");
  const requestScope = useRef<AbortController | null>(null);
  const recordsGeneration = useRef(0);

  useLayoutEffect(() => {
    const scope = new AbortController();
    requestScope.current = scope;
    acting.current = false;
    setBusy(false);
    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);
    };
  }, [owner]);

  const load = useCallback(() => {
    const request = requestScope.current?.signal;
    if (!request || request.aborted) return;
    const generation = ++recordsGeneration.current;
    setRequests(null);
    setError("");
    void getSignupRequests().then((result) => {
      if (request.aborted || generation !== recordsGeneration.current) return;
      if (result.ok) setRequests(result.data.requests);
      else setError(result.message);
    });
  }, []);
  useEffect(load, [load, owner]);
  useEffect(() => { if (approving) picker.current?.focus(); }, [approving]);

  function closePicker() {
    setApproving(null);
    setTenant("");
    opener.current?.focus();
  }
  useEscapeClose(approving !== null && !busy, closePicker);

  async function act(id: string, action: "approve" | "decline") {
    const request = requestScope.current?.signal;
    if (!request || request.aborted) return;
    const generation = recordsGeneration.current;
    if (acting.current || (action === "approve" && !companies.some((company) => company.slug === tenant))) return;
    acting.current = true;
    setBusy(true);
    setError("");
    setNotice("");
    try {
      const result = action === "approve" ? await approveSignupRequest(id, tenant) : await declineSignupRequest(id);
      if (request.aborted || generation !== recordsGeneration.current) return;
      if (!result.ok) {
        window.dispatchEvent(new CustomEvent(TOAST_EVENT, { detail: { text: result.message, tone: "error" } }));
        return;
      }
      setRequests((rows) => rows?.filter((row) => row.id !== id) ?? null);
      setApproving(null);
      setTenant("");
      if (action === "approve" && result.data.request.deliveryStatus === "failed") {
        window.dispatchEvent(new CustomEvent(TOAST_EVENT, {
          detail: { text: "Approved. The invitation could not be delivered.", tone: "error" },
        }));
      } else setNotice(action === "decline" ? "Request declined." : "Request approved.");
    } finally {
      if (!request.aborted && generation === recordsGeneration.current) {
        acting.current = false;
        setBusy(false);
      }
    }
  }

  return (
    <section className="signup-requests" aria-labelledby="signup-requests-title">
      <div className="signup-requests-head">
        <h4 id="signup-requests-title" className="padmin-h4">Sign-up requests</h4>
        <button className="signup-quiet set-secondary" type="button" onClick={load} disabled={busy || requests === null && !error}>Refresh</button>
      </div>
      {error ? <div className="set-error" role="alert"><span title={error}>Could not load sign-up requests.</span>
        <button type="button" className="set-secondary" disabled={busy} onClick={load}>Retry</button></div> : null}
      {notice ? <p className="set-help" role="status">{notice}</p> : null}
      {requests === null ? error ? null : <Skeleton rows={3} /> : requests.length === 0 ? (
        <p className="set-help">No requests.</p>
      ) : (
        <ul aria-label="Sign-up requests">
          {requests.map((request) => {
            const stamp = new Date(request.at);
            const validTime = !Number.isNaN(stamp.getTime());
            return (
              <li className="signup-request" key={request.id}>
                <div className="signup-request-row">
                  <div>
                    <span className="signup-request-phone">{request.phone}</span>
                    <time dateTime={validTime ? request.at : undefined}>
                      {validTime ? stamp.toLocaleString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }) : "Time unavailable"}
                    </time>
                  </div>
                  <p className="signup-request-text">{request.text}</p>
                  <div className="signup-request-actions">
                    <button className="signup-quiet set-secondary" type="button" disabled={busy}
                      aria-label={`Approve request from ${request.phone}`} aria-expanded={approving === request.id}
                      onClick={(event) => {
                        opener.current = event.currentTarget;
                        setApproving(request.id);
                        setTenant("");
                        setError("");
                      }}>Approve</button>
                    <button className="signup-quiet set-secondary" type="button" disabled={busy}
                      aria-label={`Decline request from ${request.phone}`}
                      onClick={() => void act(request.id, "decline")}>Decline</button>
                  </div>
                </div>
                {approving === request.id ? (
                  <form className="signup-approval" aria-label="Choose company" onSubmit={(event) => {
                    event.preventDefault();
                    void act(request.id, "approve");
                  }}>
                    <label htmlFor="signup-company">Company</label>
                    <select id="signup-company" ref={picker} value={tenant} required disabled={busy}
                      onChange={(event) => setTenant(event.target.value)}>
                      <option value="">Choose company</option>
                      {companies.map((company) => <option key={company.slug} value={company.slug}>{company.name}</option>)}
                    </select>
                    <div className="signup-request-actions">
                      <button className="signup-primary set-secondary" type="submit" disabled={busy || !tenant} aria-busy={busy}>Approve</button>
                      <button className="signup-quiet set-secondary" type="button" disabled={busy} onClick={closePicker}>Cancel</button>
                    </div>
                    {companies.length === 0 ? <p className="set-help">No companies available.</p> : null}
                  </form>
                ) : null}
              </li>
            );
          })}
        </ul>
      )}
    </section>
  );
}

export function AdminPane({ user }: { user: { username: string; name: string; role: string } }) {
  const [ov, setOv] = useState<Overview | null>(null);
  const [err, setErr] = useState("");
  const [loading, setLoading] = useState(true);
  const [fleet, setFleet] = useState<{ rows: AutomationRow[]; cost: FleetCost } | null>(null);
  const [fleetError, setFleetError] = useState("");

  const [drill, setDrill] = useState<{ kind: DrillKind; tenant: string } | null>(null);
  const [drillRows, setDrillRows] = useState<unknown[] | null>(null);
  const [drillNote, setDrillNote] = useState("");
  const [drillError, setDrillError] = useState("");

  const [aws, setAws] = useState<{ text: string; note: string; available: boolean } | null>(null);
  // Wave 20 (R6): the releases panel. Loaded with the overview rather than on demand β€” it is
  // two small Hub reads and the first question an operator opens this pane to answer.
  const [rel, setRel] = useState<ReleasesPayload | null>(null);
  const [relError, setRelError] = useState("");
  const [awsBusy, setAwsBusy] = useState(false);
  const [neon, setNeon] = useState<NeonUsage | null>(null);
  const [neonError, setNeonError] = useState("");
  const [digitalOcean, setDigitalOcean] = useState<DigitalOceanUsage | null>(null);
  const [digitalOceanError, setDigitalOceanError] = useState("");

  const load = useCallback(() => {
    setLoading(true);
    setErr("");
    setOv(null);
    setFleet(null);
    setFleetError("");
    setRel(null);
    setRelError("");
    setNeon(null);
    setNeonError("");
    setDigitalOcean(null);
    setDigitalOceanError("");
    void getOverview().then((r) => {
      setLoading(false);
      if (r.ok) {
        setOv(r.data);
        setErr("");
      } else setErr(r.message);
    });
    void getAutomations().then((r) => {
      if (r.ok) setFleet({ rows: r.data.automations, cost: r.data.cost });
      else setFleetError(r.message);
    });
    void getReleases().then((r) => {
      if (r.ok) setRel(r.data);
      else setRelError(r.message);
    });
    void getNeon().then((r) => {
      if (r.ok) { setNeon(r.data); setNeonError(""); }
      else setNeonError(r.message);
    });
    void getDigitalOcean().then((r) => {
      if (r.ok) { setDigitalOcean(r.data); setDigitalOceanError(""); }
      else setDigitalOceanError(r.message);
    });
  }, []);
  useEffect(load, [load]);

  const openDrill = useCallback((kind: DrillKind, tenant: string) => {
    setDrill({ kind, tenant });
    setDrillRows(null);
    setDrillNote("");
    setDrillError("");
    const fetcher =
      kind === "users"
        ? getUsers
        : kind === "databases"
          ? getDatabases
          : kind === "connectors"
            ? getConnectors
            : getAutomations;
    void fetcher(tenant || undefined).then((r) => {
      if (!r.ok) {
        setDrillRows([]);
        setDrillError(r.message);
        return;
      }
      const d = r.data as Record<string, unknown>;
      setDrillRows((d[kind] as unknown[]) ?? []);
      // The server's own honest note travels with the rows rather than being
      // re-invented here: it is the one that knows WHY a tenant is missing.
      const errors = (d.errors as Record<string, string>) ?? {};
      const words = Object.entries(errors).map(([t, e]) => `${t}: ${e}`);
      setDrillNote(
        [typeof d.stampsNote === "string" ? d.stampsNote : "", ...words]
          .filter(Boolean)
          .join(" Β· ")
      );
    });
  }, []);

  const loadAws = useCallback(() => {
    setAwsBusy(true);
    void getAws(7).then((r) => {
      setAwsBusy(false);
      if (r.ok) setAws(r.data.report);
      else setAws({ text: "", note: r.message, available: false });
    });
  }, []);

  return (
    <div className="set-pane">
      <h3 className="set-h">Loopable admin</h3>
      <p className="set-help set-pane-intro">Signed in as {user.name}.</p>
      <div className="set-actions">
        <button type="button" className="set-primary" disabled={loading} onClick={load}>Refresh</button>
      </div>
      {err ? <div className="set-error" role="alert"><span title={err}>Could not read the platform overview.</span>
        <button type="button" className="set-secondary" onClick={load}>Retry</button></div> : null}
      {fleetError ? <div className="set-error" role="alert"><span title={fleetError}>Could not read automation costs.</span>
        <button type="button" className="set-secondary" onClick={load}>Retry</button></div> : null}
      {relError ? <div className="set-error" role="alert"><span title={relError}>Could not read releases.</span>
        <button type="button" className="set-secondary" onClick={load}>Retry</button></div> : null}

      <SignupRequests tenants={ov?.tenants ?? []} owner={user.username} />

      {loading ? (
        <Skeleton rows={4} />
      ) : !ov ? null : (
        <>
          <div className="padmin-totals">
            <Total label="Workspaces" value={int(ov.totals.tenants)} />
            <Total label="People" value={int(ov.totals.users)} />
            <Total label="Databases" value={int(ov.totals.databases)} />
            <Total label="Records" value={int(ov.totals.rows)} />
            <Total
              label="Automation floor"
              value={fleet ? (fleet.cost.usd === 0 ? "$0.00 idle" : `~$${fleet.cost.usd.toFixed(2)}`) : "Cost has not loaded"}
              hint={fleet?.cost.basis}
            />
          </div>
          {ov.totals.unknownTenants > 0 ? (
            <p className="set-help padmin-caveat">
              {ov.totals.unknownTenants} workspace
              {ov.totals.unknownTenants === 1 ? "" : "s"} could not be read, so the totals above
              exclude {ov.totals.unknownTenants === 1 ? "it" : "them"}.
            </p>
          ) : null}

          <div className="padmin-tablewrap">
            <table className="padmin-table">
              <thead>
                <tr>
                  <th>Workspace</th>
                  <th>Storage</th>
                  <th className="padmin-num">People</th>
                  <th className="padmin-num">Databases</th>
                  <th className="padmin-num">Records</th>
                  <th className="padmin-num">Sources</th>
                  <th className="padmin-num">Automations</th>
                </tr>
              </thead>
              <tbody>
                {ov.tenants.map((t) => (
                  <tr key={t.slug}>
                    <td>
                      <span className="padmin-name">{t.name}</span>
                      <span className="padmin-meta">
                        {t.slug}
                        {t.status !== "active" ? ` Β· ${t.status}` : ""}
                        {t.errors && t.errors.length ? ` Β· ${t.errors[0]}` : ""}
                      </span>
                    </td>
                    <td>
                      <span className="padmin-meta">
                        {t.storeRepo && t.storeRepo.includes("/")
                          ? "own repository"
                          : t.storePrefix
                            ? "shared repository"
                            : "tenant #0 repository"}
                        {t.keychainLocked ? " Β· keychain locked" : ""}
                      </span>
                    </td>
                    <DrillCell
                      n={t.users}
                      onOpen={() => openDrill("users", t.slug)}
                      title={`${t.admins} administrator${t.admins === 1 ? "" : "s"}`}
                    />
                    <DrillCell
                      n={t.databases}
                      onOpen={() => openDrill("databases", t.slug)}
                      why={t.errors?.[0]}
                    />
                    <DrillCell
                      n={t.rows}
                      onOpen={() => openDrill("databases", t.slug)}
                      why={t.errors?.[0]}
                    />
                    <DrillCell
                      n={t.connectors}
                      onOpen={() => openDrill("connectors", t.slug)}
                      why={t.errors?.[0]}
                      title={
                        t.connectorsPaused ? `${t.connectorsPaused} paused` : "none paused"
                      }
                    />
                    <DrillCell
                      n={t.automations}
                      onOpen={() => openDrill("automations", t.slug)}
                      why={t.errors?.[0]}
                      title={
                        t.automationsEnabled != null
                          ? `${t.automationsEnabled} scheduled`
                          : undefined
                      }
                    />
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <p className="set-help padmin-caveat">
            Read {ago(ov.generatedAt)} in {ov.tookMs} ms.{" "}
            {ov.totals.orphanUsers > 0
              ? `${ov.totals.orphanUsers} account${
                  ov.totals.orphanUsers === 1 ? "" : "s"
                } belong to a workspace this deployment no longer knows. `
              : ""}
          </p>

          {drill ? (
            <section className="padmin-drill">
              <div className="padmin-drill-head">
                <h4 className="padmin-h4">
                  {DRILL_NOUN[drill.kind]}
                  {drill.tenant ? `: ${drill.tenant}` : ""}
                </h4>
                <button type="button" className="padmin-link set-secondary" onClick={() => setDrill(null)}>
                  Close
                </button>
              </div>
              {drillError ? <div className="set-error" role="alert"><span title={drillError}>Could not read these rows.</span>
                <button type="button" className="set-secondary" onClick={() => openDrill(drill.kind, drill.tenant)}>Retry</button></div> : drillRows === null ? (
                <Skeleton rows={2} />
              ) : drillRows.length === 0 ? (
                <p className="set-help">Nothing here yet.</p>
              ) : (
                <DrillTable kind={drill.kind} rows={drillRows} />
              )}
              {drillNote ? <p className="set-help padmin-caveat">{drillNote}</p> : null}
            </section>
          ) : null}

          {!fleet && !fleetError ? <section className="padmin-block">
            <h4 className="padmin-h4">Automation cost</h4>
            <Skeleton rows={2} />
          </section> : fleet ? (
            <section className="padmin-block">
              {/* Named for what it SHOWS. The fleet's rows live one level down,
                  behind the Automations count β€” this section is the cost and the
                  reasoning behind it, so calling it "fleet" would promise a
                  table that is deliberately not here. */}
              <h4 className="padmin-h4">Automation cost</h4>
              <p className="set-help">
                {fleet.rows.filter((a) => a.enabled).length} automations of {fleet.rows.length}
                {`, ${fleet.cost.nativeSchedules} exact schedule${fleet.cost.nativeSchedules === 1 ? "" : "s"}`}
                {fleet.cost.fleetRunsPerDay
                  ? `, about ${fleet.cost.fleetRunsPerDay} runs a day`
                  : ""}
                {fleet.cost.unknownCadence
                  ? ` (${fleet.cost.unknownCadence} on a custom cadence, not counted)`
                  : ""}
                . {fleet.cost.basis}
              </p>
            </section>
          ) : null}

          {/* ── Wave 20 (owner item 12 / R6): what is running where ──────────────────
              READ-ONLY BY RULING. The operator sees both environments and every cut
              release; moving one is a CLI command, printed below rather than wired to
              a button, so no browser session can rewrite production. */}
          <section className="padmin-block">
            <h4 className="padmin-h4">Releases</h4>
            {relError ? null : !rel ? (
              <Skeleton rows={2} />
            ) : (
              <>
                <table className="padmin-table">
                  <thead>
                    <tr>
                      <th>Environment</th>
                      <th>Version</th>
                      <th>Stage</th>
                      <th>Space</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rel.environments.map((e) => (
                      <tr key={e.env}>
                        <td>{e.env === "live" ? "Live (pinned)" : "Staging (follows the tree)"}</td>
                        {/* ⚠ An unreadable version is a NOTE, never a blank. A blank cell in a
                            column headed "Version" reads as "nothing is deployed", which about a
                            production environment is the worst available way to be wrong. */}
                        <td>{e.version || <span className="set-help">{e.note || "unknown"}</span>}</td>
                        <td>{e.stage || "Stage could not be read"}</td>
                        {/* The Space ID as TEXT, not a link: the server deliberately builds no
                            URL (portability C1 β€” a host literal in runtime code hard-codes the
                            current host into a process designed to move). */}
                        <td>{e.space}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
                {rel.releases.length ? (
                  <table className="padmin-table">
                    <thead>
                      <tr>
                        <th>Release</th>
                        <th>Commit</th>
                        <th>Cut</th>
                        <th>What shipped</th>
                      </tr>
                    </thead>
                    <tbody>
                      {rel.releases.map((r) => (
                        <tr key={r.version}>
                          <td>{r.version}</td>
                          <td>{r.sha}</td>
                          <td>{r.date}</td>
                          <td>{r.subject}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                ) : (
                  <p className="set-help">
                    No tagged releases were readable from either Space.
                  </p>
                )}
                <p className="set-help">
                  To move Live to another version, or roll it back, run:{" "}
                  <code>{rel.promote}</code>
                </p>
              </>
            )}
          </section>

          <section className="padmin-block">
            <h4 className="padmin-h4">AWS cron</h4>
            {awsBusy ? <Skeleton rows={2} /> : !aws ? (
              <p className="set-help">
                The external tick that wakes this app on schedule. Reading its usage runs a live
                CloudWatch query and takes a few seconds.{" "}
                <button
                  type="button"
                  className="padmin-link set-secondary"
                  onClick={loadAws}
                  disabled={awsBusy}
                >
                  {awsBusy ? "Reading…" : "Check usage"}
                </button>
              </p>
            ) : aws.available ? (
              <pre className="padmin-pre">{aws.text}</pre>
            ) : (
              <div className="set-error" role="alert"><span title={aws.note}>Could not read AWS usage.</span>
                <button type="button" className="set-secondary" disabled={awsBusy} onClick={loadAws}>Retry</button></div>
            )}
          </section>
        </>
      )}
      <NeonCard data={neon} error={neonError} onRetry={load} />
      <DigitalOceanCard data={digitalOcean} error={digitalOceanError} onRetry={load} />
    </div>
  );
}

function Total({ label, value, hint }: { label: string; value: string; hint?: string }) {
  // A tooltip nobody can see is a tooltip nobody reads: the label carries a
  // dotted underline exactly when there is something behind it.
  return (
    <div className={"padmin-total" + (hint ? " has-hint" : "")} title={hint || undefined}>
      <span className="padmin-total-label">{label}</span>
      <span className="padmin-total-value">{value}</span>
    </div>
  );
}

/** A numeric cell that opens its own rows. Unknown counts are not clickable β€”
 *  there is nothing to drill INTO when the read failed, and a button that opens
 *  an empty table would read as "none". */
function DrillCell({
  n,
  onOpen,
  why,
  title,
}: {
  n: number | null | undefined;
  onOpen: () => void;
  why?: string;
  title?: string;
}) {
  if (n === null || n === undefined)
    return (
      <td className="padmin-num">
        <Count n={n} why={why} />
      </td>
    );
  return (
    <td className="padmin-num">
      <button type="button" className="padmin-drill-btn set-secondary" onClick={onOpen} title={title}>
        {int(n)}
      </button>
    </td>
  );
}

function DrillTable({ kind, rows }: { kind: DrillKind; rows: unknown[] }) {
  if (kind === "users") {
    const rs = rows as PlatformUser[];
    return (
      <div className="padmin-tablewrap">
        <table className="padmin-table">
          <thead>
            <tr>
              <th>Person</th>
              <th>Workspace</th>
              <th>Role</th>
              <th>Last sign-in</th>
              <th>Last active</th>
            </tr>
          </thead>
          <tbody>
            {rs.map((u) => (
              <tr key={`${u.tenant}/${u.username}`}>
                <td>
                  <span className="padmin-name">{u.name}</span>
                  <span className="padmin-meta">
                    {u.username}
                    {u.email ? ` Β· ${u.email}` : ""}
                    {u.active ? "" : " Β· deactivated"}
                  </span>
                </td>
                <td>{u.tenant}</td>
                <td>
                  {u.role}
                  {u.platformAdmin ? " Β· platform" : ""}
                </td>
                <td>{ago(u.lastLogin)}</td>
                <td>{ago(u.lastActive)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
  if (kind === "databases") {
    const rs = rows as DatabaseRow[];
    return (
      <div className="padmin-tablewrap">
        <table className="padmin-table">
          <thead>
            <tr>
              <th>Database</th>
              <th>Workspace</th>
              <th>Built from</th>
              <th className="padmin-num">Fields</th>
              <th className="padmin-num">Records</th>
            </tr>
          </thead>
          <tbody>
            {rs.map((d) => (
              <tr key={`${d.tenant}/${d.key}`}>
                <td>
                  <span className="padmin-name">{d.label}</span>
                  <span className="padmin-meta">
                    {d.key}
                    {d.createdBy ? ` Β· ${d.createdBy}` : ""}
                  </span>
                </td>
                <td>{d.tenant}</td>
                <td>{d.source}</td>
                <td className="padmin-num">{int(d.fields)}</td>
                <td className="padmin-num">{int(d.rowCount)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
  if (kind === "connectors") {
    const rs = rows as ConnectorRow[];
    return (
      <div className="padmin-tablewrap">
        <table className="padmin-table">
          <thead>
            <tr>
              <th>Source</th>
              <th>Workspace</th>
              <th>Kind</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {rs.map((c) => (
              <tr key={`${c.tenant}/${c.key}`}>
                <td>
                  <span className="padmin-name">{c.label}</span>
                  <span className="padmin-meta">
                    {c.source === "env" ? "environment credentials" : "keychain"}
                  </span>
                </td>
                <td>{c.tenant}</td>
                <td>{c.type}</td>
                <td>
                  <span
                    className={
                      "padmin-dot " +
                      (c.paused ? "is-paused" : c.active ? "is-live" : "is-idle")
                    }
                  />
                  {c.paused ? "paused" : c.active ? "serving" : "stored"}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
  const rs = rows as AutomationRow[];
  return (
    <div className="padmin-tablewrap">
      <table className="padmin-table">
        <thead>
          <tr>
            <th>Automation</th>
            <th>Workspace</th>
            <th>Schedule</th>
            <th className="padmin-num">Runs a day</th>
            <th>Last run</th>
          </tr>
        </thead>
        <tbody>
          {rs.map((a) => (
            <tr key={`${a.tenant}/${a.id}`}>
              <td>
                <span className="padmin-name">{a.name}</span>
                <span className="padmin-meta">
                  {a.kind}
                  {a.failedRetained
                    ? ` Β· ${a.failedRetained} of the last ${a.runsRetained} runs failed`
                    : ""}
                </span>
              </td>
              <td>{a.tenant}</td>
              <td>{a.enabled ? a.cron || "scheduled" : "paused"}</td>
              <td className="padmin-num">
                {a.enabled ? (a.runsPerDay === null ? "custom" : a.runsPerDay) : "Disabled"}
              </td>
              <td>
                <span
                  className={
                    "padmin-dot " +
                    (a.state === "error" ? "is-error" : a.state === "ok" ? "is-live" : "is-idle")
                  }
                />
                {/* Verbatim, not relative: the engine writes this stamp with no
                    zone (`automation_engine._iso()` is naive local-to-container),
                    so "x hours ago" would be wrong by the viewer's offset. */}
                {a.lastRunAt ? a.lastRunAt.replace("T", " ") : "never"}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default AdminPane;