cautpartener / client / src / app / views / contacts-tab.ts
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
/**
 * Contacte tab (M2): the verified-contact book over the home-log fold.
 *  - contact list (name, 4-emoji fingerprint, group chips) + search;
 *  - invite creation (rendezvous deposit → link + QR sheet) and invite
 *    acceptance entry point (paste / QR scan → #/add/… route);
 *  - pending-invites section with TTL countdown + cancel;
 *  - contact detail sheet (fingerprint, full pub, profile link, live group
 *    membership, local rename, remove);
 *  - groups management (create / rename / delete, member counts, members);
 *  - creator-side polling of pending invites: every deposited card ≠ own runs
 *    the mandatory fingerprint-compare confirmation before addContact;
 *  - the TOFU key-change blocking sheet (shared with the #/add flow).
 *
 * All state comes from the folded home log; the tab re-renders reactively via
 * SelfRoom.onStateChanged, so contacts synced from another device appear live.
 */

import { RuntimeLimits } from "../../config";
import {
  activeContacts,
  activeGroups,
  clampName,
  groupsOfContact,
  membersOfGroup,
  myXIdentity,
  ALL_CONTACTS_GID,
  type ContactCard,
  type ContactsService,
} from "../../core/contacts";
import type { ContactOp, GroupOp, HomeState } from "../../core/home-log";
import {
  addPendingInvite,
  dismissInviteCard,
  extractInviteToken,
  inviteLink,
  inviteToken,
  isInviteCardDismissed,
  listPendingInvites,
  newInviteSecret,
  Rendezvous,
  removePendingInvite,
  inviteExpiresAt,
  type PendingInvite,
} from "../../core/rendezvous";
import { Session } from "../../core/session";
import { fingerprintOf, type Fingerprint } from "../../lib/identity";
import {
  clearCreqSent,
  dismissRequest,
  pollOwnInbox,
  sendCack,
  type IncomingAck,
  type IncomingRequest,
} from "../../public/creq-service";
import { t } from "../i18n";
import { qrElement } from "../qr";
import { h, sheet, toast } from "../ui-kit";

const PROFILE_BASE = "https://cautpartener.ro/#/u/";

// ---- fingerprint cache -------------------------------------------------------

const fpCache = new Map<string, Fingerprint>();

async function fpOf(pub: string): Promise<Fingerprint> {
  let fp = fpCache.get(pub);
  if (!fp) {
    fp = await fingerprintOf(pub);
    fpCache.set(pub, fp);
  }
  return fp;
}

/** Element that fills in the emoji fingerprint once computed. */
export function fpSpan(pub: string, cls: string, testid?: string): HTMLElement {
  const el = h("span", { class: cls, "data-testid": testid });
  void fpOf(pub).then((fp) => {
    el.textContent = fp.emoji;
    el.title = fp.hex;
  });
  return el;
}

/** My display name from the synced settings bag ("" when unset). */
export function myCardName(): string {
  const name = Session.selfroom?.state.settings.name;
  return typeof name === "string" ? clampName(name) : "";
}

async function saveMyName(name: string): Promise<void> {
  const clean = clampName(name);
  if (!clean || clean === myCardName()) return;
  await Session.selfroom?.setSettings({ name: clean }).catch(() => {});
}

/**
 * Build my own contact card (derives + certifies the X25519 pub fresh). The
 * SANITIZED name goes both into the signed cert string and, identically, into
 * the card itself (§3 — verifiers reconstruct from the card's literal name).
 */
export async function buildMyCard(name: string): Promise<ContactCard | null> {
  const id = Session.identity;
  if (!id) return null;
  const x = await myXIdentity(id.identity, id.seed, name);
  if (!x.name) return null; // empty after sanitizing — never send a nameless card
  return { pub: id.identity.publicKeyB64, xPub: x.xPub, xSig: x.xSig, name: x.name };
}

// ---- TOFU key-change warning (blocking, explicit accept/reject) --------------

/**
 * The card's xPub differs from the stored TOFU binding. Never applied
 * silently: this sheet explains the risk and only "accept" moves the binding.
 * Resolves true when the new key was accepted.
 */
export function openTofuSheet(card: ContactCard, existing: ContactOp, svc: ContactsService): Promise<boolean> {
  return new Promise((resolve) => {
    const accept = h(
      "button",
      { type: "button", class: "btn danger", "data-testid": "tofu-accept" },
      t("tofuAccept"),
    ) as HTMLButtonElement;
    const reject = h(
      "button",
      { type: "button", class: "btn ghost", "data-testid": "tofu-reject" },
      t("tofuReject"),
    ) as HTMLButtonElement;
    const body = h(
      "div",
      { "data-testid": "tofu-warning" },
      h("h2", { class: "sheet-title danger-text" }, t("tofuTitle")),
      h("p", { class: "muted" }, t("tofuBody", { name: existing.name })),
      h("div", { class: "btn-row" }, reject, accept),
    );
    const s = sheet(body);
    let settled = false;
    const done = (ok: boolean): void => {
      if (settled) return;
      settled = true;
      s.close();
      resolve(ok);
    };
    // backdrop dismiss = reject: the promise MUST settle either way, or the
    // caller's flow (and its finally blocks) would deadlock
    void s.closed.then(() => done(false));
    reject.addEventListener("click", () => {
      toast(t("tofuRejected"));
      done(false);
    });
    accept.addEventListener("click", () => {
      accept.disabled = true;
      void svc
        .acceptKeyChange(card)
        .then((r) => done(r.kind === "added"))
        .catch(() => done(false));
    });
  });
}

// ---- creator-side pending-invite polling -------------------------------------

let polling = false;
let lastPollAt = 0;
/** At most this many sequential confirm sheets per poll (§2b prompt cap). */
const PROMPT_CAP = 3;
/** Cards beyond the prompt cap, reviewable in the tab (key `pub|xPub`). */
const queuedCards = new Map<string, { card: ContactCard; secret: string }>();
/** Pubs some invite room bound to ≥2 distinct xPubs — refused (§2b). */
const ambiguousPubs = new Set<string>();
/** Last poll saw a partial mailbox view — soft "sync incomplet" hint. */
let lastPollPartial = false;

/**
 * Replay every pending invite room: heal a missing own-card deposit, then run
 * the mandatory fingerprint confirmation for each deposited card ≠ own that
 * is not already a contact — capped at PROMPT_CAP sheets per poll, the rest
 * queue into the tab's reviewable list. Called on boot (main.ts) and on tab
 * open. An invite cancelled while a poll is in flight (this tab or another)
 * is honored on the NEXT loop iteration: its tombstone hides it from
 * listPendingInvites and the re-check below skips it.
 */
export async function pollPendingInvites(onChange?: () => void): Promise<void> {
  const svc = Session.contacts;
  const id = Session.identity;
  if (!svc || !id || polling || Date.now() - lastPollAt < 10_000) return;
  polling = true;
  lastPollAt = Date.now();
  let prompts = 0;
  let partial = false;
  try {
    for (const inv of listPendingInvites()) {
      // cancel honesty: re-read the store each iteration (see docstring)
      if (!listPendingInvites().some((i) => i.secret === inv.secret)) continue;
      const rdv = await Rendezvous.open(inv.secret);
      if (!rdv) return;
      const res = await rdv.fetchCards();
      if (res === null) continue; // mailbox unreachable — retry next poll
      if (res.partial) partial = true;
      for (const pub of res.ambiguous) if (pub !== svc.myPub) ambiguousPubs.add(pub);
      if (!res.partial && !res.cards.some((c) => c.pub === svc.myPub)) {
        // initial deposit failed (or the room's copy expired) — re-arm it.
        // NEVER on a partial view: our card may sit in the unfetched pages
        // and a blind re-deposit would grow the room's blob count.
        const name = myCardName();
        if (name) {
          const mine = await buildMyCard(name);
          if (mine) void rdv.depositCard(mine).catch(() => {});
        }
      }
      for (const card of res.cards) {
        if (card.pub === svc.myPub) continue;
        if (isInviteCardDismissed(inv.secret, card.pub, card.xPub)) continue;
        if (cardAlreadyActive(card, svc)) continue; // already added (current fold)
        const key = `${card.pub}|${card.xPub}`;
        if (prompts >= PROMPT_CAP) {
          // over the cap — aggregate into the tab's reviewable list instead
          queuedCards.set(key, { card, secret: inv.secret });
          onChange?.();
          continue;
        }
        prompts++;
        queuedCards.delete(key);
        await promptJoinedCard(card, inv.secret, svc);
        onChange?.();
      }
    }
  } finally {
    lastPollPartial = partial;
    polling = false;
  }
}

/** Is this card already a confirmed contact under the CURRENT fold? */
function cardAlreadyActive(card: ContactCard, svc: ContactsService): boolean {
  const existing = svc.state.contacts.get(card.pub);
  return existing?.status === "active" && existing.xPub === card.xPub;
}

/**
 * Mandatory fingerprint-compare confirmation for one deposited card. Always
 * settles: a backdrop dismiss counts as "not now" (no persisted dismissal, so
 * the card may re-prompt on a later poll) — the caller's finally must run.
 */
async function promptJoinedCard(card: ContactCard, secret: string, svc: ContactsService): Promise<void> {
  const fp = await fpOf(card.pub);
  // Poll-race guard (M6): the boot poll can fetch a card BEFORE the home-log
  // fold has replayed the contact op that already confirmed it (this device
  // earlier, or another device while both are online). Re-check against the
  // CURRENT fold after every await and skip — never re-prompt a confirmed card.
  if (cardAlreadyActive(card, svc)) return;
  await new Promise<void>((resolve) => {
    const yes = h(
      "button",
      { type: "button", class: "btn", "data-testid": "invite-confirm-yes" },
      t("addConfirm"),
    ) as HTMLButtonElement;
    const no = h("button", { type: "button", class: "btn ghost", "data-testid": "invite-confirm-no" }, t("cancel"));
    const body = h(
      "div",
      { "data-testid": "invite-confirm" },
      h("h2", { class: "sheet-title" }, t("inviteJoined", { name: clampName(card.name) })),
      h("div", { class: "fp-emoji", "data-testid": "invite-confirm-fp", title: fp.hex }, fp.emoji),
      h("p", { class: "muted" }, t("addCompareBody")),
      h("div", { class: "btn-row" }, no, yes),
    );
    const s = sheet(body);
    let settled = false;
    let deciding = false; // the yes-flow may close this sheet to open TOFU
    const done = (): void => {
      if (settled) return;
      settled = true;
      unsub?.();
      s.close();
      resolve();
    };
    // fold catch-up while the sheet is open (e.g. the confirmation this card
    // represents replays from the mailbox mid-prompt) — dismiss it silently
    const unsub = Session.selfroom?.onStateChanged(() => {
      if (!deciding && cardAlreadyActive(card, svc)) done();
    });
    void s.closed.then(() => {
      if (!deciding) done(); // backdrop dismiss — settle, never deadlock
    });
    no.addEventListener("click", () => {
      dismissInviteCard(secret, card.pub, card.xPub); // persisted per invite
      done();
    });
    yes.addEventListener("click", () => {
      yes.disabled = true;
      deciding = true;
      void (async () => {
        const r = await svc.addContact(card);
        if (r.kind === "added") toast(t("ctAdded"));
        else if (r.kind === "key-change") {
          s.close();
          const accepted = await openTofuSheet(card, r.existing, svc);
          if (accepted) toast(t("ctAdded"));
          else dismissInviteCard(secret, card.pub, card.xPub);
        }
        done();
      })().catch(done);
    });
  });
}

// ---- public contact requests (creq/cack, M4) ----------------------------------

let inboxPolling = false;
let lastInboxPollAt = 0;
/** Pending incoming requests from the last inbox poll (owner side). */
let contactRequests: IncomingRequest[] = [];
/** The last poll hit a spam cap — the list may be partial (honest "and more"). */
let contactRequestsCapped = false;
/** Callers that asked for a refresh while a poll was already in flight. */
const notifyAfterInboxPoll: (() => void)[] = [];

/**
 * Poll the OWN public inboxRoom: surface incoming contact requests (creq) in
 * the tab and run the requester-side cack confirmations (fingerprint sheet →
 * contact stored, TOFU rules apply). Called on boot (main.ts) and on tab
 * open, throttled like the rendezvous poll.
 */
export async function pollContactRequests(onChange?: () => void): Promise<void> {
  const svc = Session.contacts;
  const id = Session.identity;
  if (!svc || !id) return;
  if (inboxPolling) {
    // a poll is in flight (boot) — notify this caller when it lands so the
    // tab re-renders with the fresh request list instead of a stale snapshot
    if (onChange) notifyAfterInboxPoll.push(onChange);
    return;
  }
  if (Date.now() - lastInboxPollAt < 10_000) {
    onChange?.(); // fresh enough — render from the module state
    return;
  }
  inboxPolling = true;
  lastInboxPollAt = Date.now();
  try {
    const view = await pollOwnInbox();
    if (!view.reached) return;
    contactRequests = view.requests;
    contactRequestsCapped = view.capped;
    onChange?.();
    // requester side: acks for requests we sent — confirm (capped like §2b)
    let prompts = 0;
    for (const ack of view.acks) {
      if (prompts >= PROMPT_CAP) break;
      prompts++;
      await promptCack(ack, svc);
      onChange?.();
    }
  } finally {
    inboxPolling = false;
    const waiting = notifyAfterInboxPoll.splice(0);
    for (const fn of waiting) {
      try {
        fn();
      } catch {}
    }
  }
}

/** Requester side: the target accepted — mandatory fingerprint confirmation. */
async function promptCack(ack: IncomingAck, svc: ContactsService): Promise<void> {
  const fp = await fpOf(ack.pub);
  await new Promise<void>((resolve) => {
    const yes = h("button", { type: "button", class: "btn", "data-testid": "cack-confirm-yes" }, t("addConfirm")) as HTMLButtonElement;
    const no = h("button", { type: "button", class: "btn ghost", "data-testid": "cack-confirm-no" }, t("cancel"));
    const body = h(
      "div",
      { "data-testid": "cack-confirm" },
      h("h2", { class: "sheet-title" }, t("crAckTitle", { name: clampName(ack.name) })),
      h("div", { class: "fp-emoji", "data-testid": "cack-confirm-fp", title: fp.hex }, fp.emoji),
      h("p", { class: "muted" }, t("addCompareBody")),
      h("div", { class: "btn-row" }, no, yes),
    );
    const s = sheet(body);
    let settled = false;
    let deciding = false;
    const done = (): void => {
      if (settled) return;
      settled = true;
      s.close();
      resolve();
    };
    void s.closed.then(() => {
      if (!deciding) done(); // backdrop dismiss — re-prompts on a later poll
    });
    no.addEventListener("click", done);
    yes.addEventListener("click", () => {
      yes.disabled = true;
      deciding = true;
      void (async () => {
        const card: ContactCard = { pub: ack.pub, xPub: ack.xPub, xSig: ack.xSig, name: ack.name };
        const r = await svc.addContact(card);
        if (r.kind === "added" || r.kind === "unchanged") {
          clearCreqSent(ack.pub);
          toast(t("ctAdded"));
        } else if (r.kind === "key-change") {
          s.close();
          const accepted = await openTofuSheet(card, r.existing, svc);
          if (accepted) {
            clearCreqSent(ack.pub);
            toast(t("ctAdded"));
          }
        }
        done();
      })().catch(done);
    });
  });
}

/** Owner side: fingerprint-compare + accept sheet for one incoming request. */
function openRequestSheet(req: IncomingRequest, svc: ContactsService, refresh: () => void): void {
  void (async () => {
    const fp = await fpOf(req.pub);
    const nameInput = h("input", {
      type: "text",
      class: "text-input",
      maxlength: 40,
      autocomplete: "name",
      placeholder: t("ctInviteNamePh"),
      value: myCardName(),
      "data-testid": "creq-accept-name",
    }) as HTMLInputElement;
    const yes = h("button", { type: "button", class: "btn", "data-testid": "creq-accept" }, t("addConfirm")) as HTMLButtonElement;
    const no = h("button", { type: "button", class: "btn ghost", "data-testid": "creq-accept-cancel" }, t("cancel"));
    const body = h(
      "div",
      { "data-testid": "creq-confirm" },
      h("h2", { class: "sheet-title" }, t("crAcceptTitle", { name: clampName(req.name) })),
      h("div", { class: "fp-emoji", "data-testid": "creq-confirm-fp", title: fp.hex }, fp.emoji),
      req.msg ? h("p", { class: "add-msg", "data-testid": "creq-confirm-msg" }, req.msg) : null,
      h("p", { class: "muted" }, t("addCompareBody")),
      h("label", { class: "field-label" }, t("ctInviteNameLabel")),
      nameInput,
      h("div", { class: "btn-row" }, no, yes),
    );
    const s = sheet(body);
    const gate = (): void => {
      yes.disabled = clampName(nameInput.value).length === 0;
    };
    nameInput.addEventListener("input", gate);
    gate();
    no.addEventListener("click", () => s.close());
    yes.addEventListener("click", () => {
      yes.disabled = true;
      void (async () => {
        const myName = clampName(nameInput.value);
        await Session.selfroom?.setSettings({ name: myName }).catch(() => {});
        const card: ContactCard = { pub: req.pub, xPub: req.xPub, xSig: req.xSig, name: req.name };
        let stored = false;
        const r = await svc.addContact(card);
        if (r.kind === "added" || r.kind === "unchanged") stored = true;
        else if (r.kind === "key-change") {
          s.close();
          stored = await openTofuSheet(card, r.existing, svc);
        }
        if (!stored) {
          s.close();
          return;
        }
        // deposit the ack into the requester's inbox so their side completes
        const acked = await sendCack(req.pub, myName).catch(() => false);
        if (!acked) toast(t("crAckFailed"));
        else toast(t("ctAdded"));
        contactRequests = contactRequests.filter((x) => x.pub !== req.pub);
        refresh();
        s.close();
      })().catch(() => {
        yes.disabled = false;
      });
    });
  })();
}

/** Incoming contact requests (public inbox) — reviewable one by one. */
function requestsSection(refresh: () => void): HTMLElement | null {
  const svc = Session.contacts;
  if (!svc || contactRequests.length === 0) return null;
  const rows = contactRequests.map((req) => {
    const review = h(
      "button",
      {
        type: "button",
        class: "btn ghost small",
        "data-testid": "creq-review",
        onclick: () => openRequestSheet(req, svc, refresh),
      },
      t("ctQueuedReview"),
    );
    const dismiss = h(
      "button",
      {
        type: "button",
        class: "btn ghost small danger-ghost",
        "data-testid": "creq-dismiss",
        onclick: () => {
          dismissRequest(req.pub, req.xPub);
          contactRequests = contactRequests.filter((x) => x.pub !== req.pub);
          refresh();
        },
      },
      t("ctQueuedDismiss"),
    );
    return h(
      "div",
      { class: "pending-row", "data-testid": "creq-row", "data-pub": req.pub },
      fpSpan(req.pub, "fp-small", "creq-fp"),
      h(
        "span",
        { class: "contact-name creq-main" },
        clampName(req.name),
        req.msg ? h("span", { class: "muted creq-msg" }, ` — ${req.msg}`) : null,
      ),
      review,
      dismiss,
    );
  });
  return h(
    "section",
    { class: "card" },
    h("h2", {}, t("crTitle")),
    h("p", { class: "muted small-note" }, t("crHint")),
    ...rows,
    contactRequestsCapped ? h("p", { class: "muted small-note", "data-testid": "creq-more" }, t("crMore")) : null,
  );
}

// ---- invite creation ---------------------------------------------------------

function openCreateInviteSheet(refresh: () => void): void {
  const svc = Session.contacts;
  const id = Session.identity;
  if (!svc || !id) return;

  const nameInput = h("input", {
    type: "text",
    class: "text-input",
    maxlength: 40,
    autocomplete: "name",
    placeholder: t("ctInviteNamePh"),
    value: myCardName(),
    "data-testid": "invite-name",
  }) as HTMLInputElement;
  const next = h("button", { type: "button", class: "btn", "data-testid": "invite-name-ok" }, t("onbContinue")) as HTMLButtonElement;
  const cancel = h("button", { type: "button", class: "btn ghost" }, t("cancel"));

  const body = h(
    "div",
    {},
    h("h2", { class: "sheet-title" }, t("ctInvite")),
    h("label", { class: "field-label" }, t("ctInviteNameLabel")),
    nameInput,
    h("div", { class: "btn-row" }, cancel, next),
  );
  const s = sheet(body);
  cancel.addEventListener("click", () => s.close());

  const gate = (): void => {
    next.disabled = clampName(nameInput.value).length === 0;
  };
  nameInput.addEventListener("input", gate);
  gate();

  next.addEventListener("click", () => {
    const name = clampName(nameInput.value);
    if (!name) return;
    next.disabled = true;
    void (async () => {
      await saveMyName(name);
      const secret = newInviteSecret();
      const link = inviteLink(secret, svc.myPub);
      addPendingInvite(secret);
      refresh(); // pending section shows it immediately

      // deposit the creator card right away; a failure is healed by the poll
      const mine = await buildMyCard(name);
      const rdv = await Rendezvous.open(secret);
      if (mine && rdv) {
        void rdv.depositCard(mine).then(
          (ok) => {
            if (!ok) toast(t("ctInviteFailed"));
          },
          () => toast(t("ctInviteFailed")),
        );
      } else {
        toast(t("ctInviteFailed"));
      }

      body.replaceChildren(
        h("h2", { class: "sheet-title" }, t("ctInviteTitle")),
        h("p", { class: "muted" }, t("ctInviteExplain", { hours: RuntimeLimits.ttlHours })),
        h("p", { class: "mono link-text", "data-testid": "invite-link" }, link),
        h(
          "div",
          { class: "btn-row" },
          h(
            "button",
            {
              type: "button",
              class: "btn ghost",
              "data-testid": "invite-copy",
              onclick: () => {
                void navigator.clipboard?.writeText(link).then(
                  () => toast(t("linkCopied")),
                  () => toast(t("copyFailed")),
                );
              },
            },
            t("copyLink"),
          ),
        ),
        qrElement(link, "invite-qr"),
        h("div", { class: "btn-row" }, h("button", { type: "button", class: "btn ghost", onclick: () => s.close() }, t("closeSheet"))),
      );
    })().catch(() => {
      toast(t("ctInviteFailed"));
      s.close();
    });
  });
}

// ---- invite acceptance entry point (paste / scan → #/add route) --------------

interface DetectedBarcode {
  rawValue: string;
}
interface BarcodeDetectorLike {
  detect(source: CanvasImageSource): Promise<DetectedBarcode[]>;
}
type BarcodeDetectorCtor = (new (opts?: { formats?: string[] }) => BarcodeDetectorLike) & {
  getSupportedFormats?: () => Promise<string[]>;
};

function barcodeDetectorCtor(): BarcodeDetectorCtor | null {
  return (window as unknown as { BarcodeDetector?: BarcodeDetectorCtor }).BarcodeDetector ?? null;
}

async function qrScanSupported(): Promise<boolean> {
  const BD = barcodeDetectorCtor();
  if (!BD || !navigator.mediaDevices?.getUserMedia) return false;
  try {
    return ((await BD.getSupportedFormats?.()) ?? []).includes("qr_code");
  } catch {
    return false;
  }
}

function openReceivedSheet(): void {
  const input = h("textarea", {
    class: "seed-input mono",
    rows: 3,
    placeholder: t("ctPastePh"),
    autocomplete: "off",
    autocapitalize: "off",
    spellcheck: false,
    "data-testid": "invite-paste",
  }) as HTMLTextAreaElement;
  const error = h("p", { class: "field-error", "data-testid": "invite-paste-error", hidden: true }, t("ctPasteInvalid"));
  const open = h(
    "button",
    { type: "button", class: "btn", disabled: true, "data-testid": "invite-open" },
    t("ctOpenInvite"),
  ) as HTMLButtonElement;
  const scan = h(
    "button",
    { type: "button", class: "btn ghost", hidden: true, "data-testid": "invite-scan" },
    t("onbScanQr"),
  ) as HTMLButtonElement;

  const validate = (): void => {
    const ref = extractInviteToken(input.value);
    error.hidden = ref !== null || input.value.trim().length === 0;
    open.disabled = ref === null;
  };
  input.addEventListener("input", validate);

  const body = h(
    "div",
    {},
    h("h2", { class: "sheet-title" }, t("ctPasteTitle")),
    h("p", { class: "muted" }, t("ctPasteExplain")),
    input,
    error,
    h("div", { class: "btn-row" }, scan, open),
  );
  const s = sheet(body);

  void qrScanSupported().then((ok) => (scan.hidden = !ok));
  scan.addEventListener("click", () => openInviteScanSheet(input, validate));

  open.addEventListener("click", () => {
    const ref = extractInviteToken(input.value);
    if (!ref) return;
    s.close();
    location.hash = `#/add/${inviteToken(ref.secret, ref.creatorPub)}`;
  });
}

/** Camera QR scan for invite links (BarcodeDetector, feature-detected). */
function openInviteScanSheet(input: HTMLTextAreaElement, onFilled: () => void): void {
  const BD = barcodeDetectorCtor();
  if (!BD) return;
  const video = h("video", { class: "scan-video", playsinline: true, muted: true }) as HTMLVideoElement;
  const body = h("div", {}, h("h2", { class: "sheet-title" }, t("onbScanQr")), video);
  const s = sheet(body);
  let stream: MediaStream | null = null;
  let timer: ReturnType<typeof setInterval> | null = null;
  const stop = (): void => {
    if (timer) clearInterval(timer);
    timer = null;
    stream?.getTracks().forEach((tr) => tr.stop());
    stream = null;
  };
  const obs = new MutationObserver(() => {
    if (!document.body.contains(video)) {
      stop();
      obs.disconnect();
    }
  });
  obs.observe(document.body, { childList: true, subtree: true });

  void navigator.mediaDevices
    .getUserMedia({ video: { facingMode: "environment" } })
    .then((st) => {
      stream = st;
      video.srcObject = st;
      return video.play();
    })
    .then(() => {
      const detector = new BD({ formats: ["qr_code"] });
      timer = setInterval(() => {
        void detector
          .detect(video)
          .then((codes) => {
            const hit = codes.find((c) => extractInviteToken(c.rawValue) !== null);
            if (hit) {
              input.value = hit.rawValue.trim();
              stop();
              s.close();
              onFilled();
            }
          })
          .catch(() => {});
      }, 350);
    })
    .catch(() => {
      toast(t("onbScanFail"));
      stop();
      s.close();
    });
}

// ---- contact detail sheet ----------------------------------------------------

export function openContactSheet(pub: string, refresh: () => void): void {
  const svc = Session.contacts;
  if (!svc) return;
  const c = svc.state.contacts.get(pub);
  if (!c || c.status !== "active") return;
  const link = `${PROFILE_BASE}${pub}`;

  const groupRows = (): HTMLElement => {
    const groups = activeGroups(svc.state);
    if (groups.length === 0) return h("p", { class: "muted" }, t("ctNoGroups"));
    const wrap = h("div", { class: "check-col" });
    for (const g of groups) {
      if (g.gid === ALL_CONTACTS_GID) {
        // the automatic contacts-only group: READ-ONLY here — no checkbox
        // (membership follows the contact book). The ONE allowed action is
        // manual EXCLUSION, which runs the normal setMembership-off rekey
        // path and is respected by ensureAllContactsGroup (never silently
        // re-enrolled).
        const m = svc.state.gmembers.get(`${g.gid}|${pub}`);
        const member = m?.on === true;
        const excludedTag = (): HTMLElement =>
          h("span", { class: "muted", "data-testid": "detail-group-excluded" }, t("ctAllContactsExcluded"));
        let action: HTMLElement;
        if (member) {
          const excludeBtn = h(
            "button",
            { type: "button", class: "btn ghost small danger-ghost", "data-testid": "detail-group-exclude" },
            t("ctAllContactsExclude"),
          ) as HTMLButtonElement;
          excludeBtn.addEventListener("click", () => {
            excludeBtn.disabled = true;
            void svc
              .setMembership(g.gid, pub, false)
              .then(() => {
                refresh();
                excludeBtn.replaceWith(excludedTag());
              })
              .catch(() => {
                excludeBtn.disabled = false;
              });
          });
          action = excludeBtn;
        } else if (m?.on === false) {
          action = excludedTag(); // explicit exclusion — shown honestly
        } else {
          // active contact not (yet) enrolled — the next contacts-only
          // publish's ensureAllContactsGroup pass will enroll them
          action = h("span", { class: "muted" }, "—");
        }
        wrap.append(
          h(
            "div",
            { class: "check-row", "data-testid": "detail-group-auto", "data-gid": g.gid },
            h("span", {}, g.name),
            action,
          ),
          h("p", { class: "muted small-note" }, t("ctAllContactsAuto")),
        );
        continue;
      }
      const box = h("input", { type: "checkbox", "data-gid": g.gid }) as HTMLInputElement;
      box.checked = svc.state.gmembers.get(`${g.gid}|${pub}`)?.on === true;
      box.addEventListener("change", () => {
        void svc.setMembership(g.gid, pub, box.checked).then(refresh).catch(() => {});
      });
      wrap.append(h("label", { class: "check-row", "data-testid": "detail-group", "data-gid": g.gid }, box, h("span", {}, g.name)));
    }
    return wrap;
  };

  const renameInput = h("input", {
    type: "text",
    class: "text-input",
    maxlength: 40,
    value: c.name,
    placeholder: t("ctRenamePh"),
    "data-testid": "detail-rename",
  }) as HTMLInputElement;
  const renameSave = h(
    "button",
    {
      type: "button",
      class: "btn ghost",
      "data-testid": "detail-rename-save",
      onclick: () => {
        void svc.renameContact(pub, renameInput.value).then(() => {
          refresh();
          s.close();
        });
      },
    },
    t("ctSave"),
  );

  const removeBtn = h("button", { type: "button", class: "btn ghost danger-ghost", "data-testid": "detail-remove" }, t("ctRemove"));
  const body = h(
    "div",
    { "data-testid": "contact-detail" },
    h("h2", { class: "sheet-title" }, c.name),
    h("div", { class: "fp-block" }, fpSpan(pub, "fp-emoji", "detail-fp"), h("div", { class: "muted fp-hint" }, t("onbFingerprintHint"))),
    h("p", { class: "mono detail-pub", "data-testid": "detail-pub" }, pub),
    h("p", {}, h("span", { class: "muted" }, `${t("ctDetailLink")}: `)),
    h("p", { class: "mono link-text", "data-testid": "detail-link" }, link),
    h(
      "div",
      { class: "btn-row" },
      h(
        "button",
        {
          type: "button",
          class: "btn ghost",
          "data-testid": "detail-copy-link",
          onclick: () => {
            void navigator.clipboard?.writeText(link).then(
              () => toast(t("linkCopied")),
              () => toast(t("copyFailed")),
            );
          },
        },
        t("copyLink"),
      ),
    ),
    h("h3", { class: "sheet-sub" }, t("ctDetailGroups")),
    groupRows(),
    h("h3", { class: "sheet-sub" }, t("ctGroupRename")),
    h("div", { class: "row-gap" }, renameInput, renameSave),
    h("div", { class: "btn-row spaced-top" }, removeBtn),
  );
  const s = sheet(body);

  removeBtn.addEventListener("click", () => {
    const yes = h("button", { type: "button", class: "btn danger", "data-testid": "detail-remove-yes" }, t("ctRemove"));
    const no = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
    body.replaceChildren(
      h("h2", { class: "sheet-title" }, t("ctRemove")),
      h("p", { class: "muted" }, t("ctRemoveConfirm", { name: c.name })),
      h("div", { class: "btn-row" }, no, yes),
    );
    no.addEventListener("click", () => s.close());
    yes.addEventListener("click", () => {
      void svc.removeContact(pub).then(() => {
        toast(t("ctRemovedToast"));
        refresh();
        s.close();
      });
    });
  });
}

// ---- groups management -------------------------------------------------------

function openNameSheet(title: string, initial: string, testid: string, onSave: (name: string) => void): void {
  const input = h("input", {
    type: "text",
    class: "text-input",
    maxlength: 40,
    value: initial,
    placeholder: t("ctGroupNamePh"),
    "data-testid": `${testid}-input`,
  }) as HTMLInputElement;
  const save = h("button", { type: "button", class: "btn", "data-testid": `${testid}-ok` }, t("ctSave")) as HTMLButtonElement;
  const cancel = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
  const body = h("div", {}, h("h2", { class: "sheet-title" }, title), input, h("div", { class: "btn-row" }, cancel, save));
  const s = sheet(body);
  const gate = (): void => {
    save.disabled = clampName(input.value).length === 0;
  };
  input.addEventListener("input", gate);
  gate();
  cancel.addEventListener("click", () => s.close());
  save.addEventListener("click", () => {
    const name = clampName(input.value);
    if (!name) return;
    s.close();
    onSave(name);
  });
}

function openGroupSheet(gid: string, refresh: () => void): void {
  const svc = Session.contacts;
  if (!svc) return;
  const g = svc.state.groups.get(gid);
  if (!g || g.status !== "active") return;
  const members = membersOfGroup(svc.state, gid);

  // The automatic contacts-only group (P1): READ-ONLY — no rename, no delete
  // (membership follows the contact book; the honest difference is stated).
  // The ONE allowed action is manual per-member EXCLUSION, wired through the
  // normal setMembership-off rekey path and respected by
  // ensureAllContactsGroup (never silently re-enrolled).
  if (gid === ALL_CONTACTS_GID) {
    const memberList =
      members.length === 0
        ? h("p", { class: "muted" }, t("ctGroupEmpty"))
        : h(
            "div",
            { class: "member-list" },
            ...members.map((m) => {
              const excludeBtn = h(
                "button",
                { type: "button", class: "btn ghost small danger-ghost", "data-testid": "group-exclude", "data-pub": m.pub },
                t("ctAllContactsExclude"),
              ) as HTMLButtonElement;
              const row = h(
                "div",
                { class: "member-row", "data-testid": "group-member", "data-pub": m.pub },
                fpSpan(m.pub, "fp-small"),
                h("span", {}, m.name),
                excludeBtn,
              );
              excludeBtn.addEventListener("click", () => {
                excludeBtn.disabled = true;
                void svc
                  .setMembership(gid, m.pub, false)
                  .then(() => {
                    row.remove();
                    refresh();
                  })
                  .catch(() => {
                    excludeBtn.disabled = false;
                  });
              });
              return row;
            }),
          );
    sheet(
      h(
        "div",
        { "data-testid": "group-detail-auto" },
        h("h2", { class: "sheet-title" }, g.name),
        h("p", { class: "muted" }, t("ctGroupMembers", { n: members.length })),
        h("p", { class: "muted small-note", "data-testid": "group-auto-note" }, t("ctAllContactsNote")),
        memberList,
      ),
    );
    return;
  }

  const renameBtn = h(
    "button",
    {
      type: "button",
      class: "btn ghost",
      "data-testid": "group-rename",
      onclick: () => {
        s.close();
        openNameSheet(t("ctGroupRename"), g.name, "group-rename", (name) => {
          void svc.renameGroup(gid, name).then(refresh);
        });
      },
    },
    t("ctGroupRename"),
  );
  const deleteBtn = h("button", { type: "button", class: "btn ghost danger-ghost", "data-testid": "group-delete" }, t("ctGroupDelete"));

  const memberList =
    members.length === 0
      ? h("p", { class: "muted" }, t("ctGroupEmpty"))
      : h(
          "div",
          { class: "member-list" },
          ...members.map((m) =>
            h("div", { class: "member-row", "data-testid": "group-member", "data-pub": m.pub }, fpSpan(m.pub, "fp-small"), h("span", {}, m.name)),
          ),
        );

  const body = h(
    "div",
    { "data-testid": "group-detail" },
    h("h2", { class: "sheet-title" }, g.name),
    h("p", { class: "muted" }, t("ctGroupMembers", { n: members.length })),
    memberList,
    h("div", { class: "btn-row spaced-top" }, renameBtn, deleteBtn),
  );
  const s = sheet(body);

  deleteBtn.addEventListener("click", () => {
    const yes = h("button", { type: "button", class: "btn danger", "data-testid": "group-delete-yes" }, t("ctGroupDelete"));
    const no = h("button", { type: "button", class: "btn ghost" }, t("cancel"));
    body.replaceChildren(
      h("h2", { class: "sheet-title" }, t("ctGroupDelete")),
      h("p", { class: "muted" }, t("ctGroupDeleteConfirm", { name: g.name })),
      h("div", { class: "btn-row" }, no, yes),
    );
    no.addEventListener("click", () => s.close());
    yes.addEventListener("click", () => {
      void svc.deleteGroup(gid).then(() => {
        refresh();
        s.close();
      });
    });
  });
}

// ---- the tab -----------------------------------------------------------------

let searchQuery = ""; // survives re-renders

function fmtRemaining(ms: number): string {
  const d = Math.floor(ms / 86_400_000);
  const hs = Math.floor((ms % 86_400_000) / 3_600_000);
  if (d > 0) return t("ctExpDh", { d, h: hs });
  if (hs > 0) return t("ctExpH", { h: hs });
  return t("ctExpSoon");
}

function pendingSection(refresh: () => void): HTMLElement | null {
  const invites = listPendingInvites();
  if (invites.length === 0) return null;
  const svc = Session.contacts;
  const rows = invites.map((inv: PendingInvite) => {
    const remaining = fmtRemaining(inviteExpiresAt(inv) - Date.now());
    const reopen = h(
      "button",
      {
        type: "button",
        class: "btn ghost small",
        "data-testid": "pending-copy",
        onclick: () => {
          if (!svc) return;
          const link = inviteLink(inv.secret, svc.myPub);
          void navigator.clipboard?.writeText(link).then(
            () => toast(t("linkCopied")),
            () => toast(t("copyFailed")),
          );
        },
      },
      t("copyLink"),
    );
    const cancel = h(
      "button",
      {
        type: "button",
        class: "btn ghost small danger-ghost",
        "data-testid": "pending-cancel",
        onclick: () => {
          removePendingInvite(inv.secret);
          refresh();
        },
      },
      t("cancel"),
    );
    return h(
      "div",
      { class: "pending-row", "data-testid": "pending-invite" },
      h("span", { class: "muted", "data-testid": "pending-expiry" }, t("ctPendingExpires", { time: remaining })),
      reopen,
      cancel,
    );
  });
  return h(
    "section",
    { class: "card" },
    h("h2", {}, t("ctPendingTitle")),
    h("p", { class: "muted small-note" }, t("ctPendingHint")),
    ...rows,
  );
}

/**
 * Poll notices: the aggregated ambiguous-identity warning (a room bound one
 * pub to ≥2 xPubs — those cards were refused, §2b) and the soft
 * "sync incomplet" hint after a partial mailbox view.
 */
function noticesSection(): HTMLElement | null {
  if (ambiguousPubs.size === 0 && !lastPollPartial) return null;
  return h(
    "section",
    { class: "card" },
    ambiguousPubs.size > 0
      ? h("p", { class: "seed-warn", "data-testid": "ambiguous-warning" }, t("ctAmbiguousWarn", { n: ambiguousPubs.size }))
      : null,
    lastPollPartial ? h("p", { class: "muted small-note", "data-testid": "partial-sync" }, t("ctPartialSync")) : null,
  );
}

/** Cards beyond the per-poll prompt cap: reviewable one by one (§2b). */
function queuedSection(refresh: () => void): HTMLElement | null {
  const svc = Session.contacts;
  if (!svc || queuedCards.size === 0) return null;
  const rows = [...queuedCards.entries()].map(([key, { card, secret }]) => {
    const review = h(
      "button",
      {
        type: "button",
        class: "btn ghost small",
        "data-testid": "queued-review",
        onclick: () => {
          void promptJoinedCard(card, secret, svc).then(() => {
            queuedCards.delete(key);
            refresh();
          });
        },
      },
      t("ctQueuedReview"),
    );
    const dismiss = h(
      "button",
      {
        type: "button",
        class: "btn ghost small danger-ghost",
        "data-testid": "queued-dismiss",
        onclick: () => {
          dismissInviteCard(secret, card.pub, card.xPub);
          queuedCards.delete(key);
          refresh();
        },
      },
      t("ctQueuedDismiss"),
    );
    return h(
      "div",
      { class: "pending-row", "data-testid": "queued-card", "data-pub": card.pub },
      fpSpan(card.pub, "fp-small", "queued-fp"),
      h("span", { class: "contact-name" }, clampName(card.name)),
      review,
      dismiss,
    );
  });
  return h(
    "section",
    { class: "card" },
    h("h2", {}, t("ctQueuedTitle")),
    h("p", { class: "muted small-note" }, t("ctQueuedHint")),
    ...rows,
  );
}

function contactList(state: HomeState, refresh: () => void): HTMLElement {
  const all = activeContacts(state);
  const q = searchQuery.trim().toLowerCase();
  const shown = q ? all.filter((c) => c.name.toLowerCase().includes(q)) : all;
  if (all.length === 0) return h("p", { class: "muted empty-note", "data-testid": "contacts-empty" }, t("ctEmpty"));
  if (shown.length === 0) return h("p", { class: "muted empty-note" }, t("ctNoMatch"));
  const list = h("div", { class: "contact-list" });
  for (const c of shown) {
    const chips = groupsOfContact(state, c.pub).map((g) => h("span", { class: "chip", "data-gid": g.gid }, g.name));
    list.append(
      h(
        "button",
        {
          type: "button",
          class: "contact-row",
          "data-testid": "contact-row",
          "data-pub": c.pub,
          onclick: () => openContactSheet(c.pub, refresh),
        },
        fpSpan(c.pub, "fp-small", "contact-fp"),
        h("span", { class: "contact-name" }, c.name),
        chips.length > 0 ? h("span", { class: "chip-row" }, ...chips) : null,
      ),
    );
  }
  return list;
}

function groupsSection(state: HomeState, refresh: () => void): HTMLElement {
  const groups = activeGroups(state);
  const createBtn = h(
    "button",
    {
      type: "button",
      class: "btn ghost small",
      "data-testid": "group-create",
      onclick: () =>
        openNameSheet(t("ctGroupCreate"), "", "group-create", (name) => {
          void Session.contacts?.createGroup(name).then(refresh);
        }),
    },
    t("ctGroupCreate"),
  );
  const rows =
    groups.length === 0
      ? [h("p", { class: "muted" }, t("ctNoGroups"))]
      : groups.map((g: GroupOp) =>
          h(
            "button",
            {
              type: "button",
              class: "group-row",
              "data-testid": "group-row",
              "data-gid": g.gid,
              onclick: () => openGroupSheet(g.gid, refresh),
            },
            h("span", { class: "contact-name" }, g.name),
            g.gid === ALL_CONTACTS_GID ? h("span", { class: "chip", "data-testid": "group-auto-chip" }, t("ctAllContactsChip")) : null,
            h("span", { class: "muted" }, t("ctGroupMembers", { n: membersOfGroup(state, g.gid).length })),
          ),
        );
  return h("section", { class: "card" }, h("div", { class: "card-head" }, h("h2", {}, t("ctGroupsTitle")), createBtn), ...rows);
}

/**
 * Run `cleanup` the moment `el` leaves the document — a MutationObserver on
 * body, so listeners/intervals detach immediately on tab switch or route
 * change instead of lingering until their next tick.
 */
function onDisconnect(el: HTMLElement, cleanup: () => void): void {
  const obs = new MutationObserver(() => {
    if (!el.isConnected) {
      obs.disconnect();
      cleanup();
    }
  });
  obs.observe(document.body, { childList: true, subtree: true });
}

export function renderContactsTab(container: HTMLElement): void {
  const svc = Session.contacts;
  if (!svc || !Session.selfroom) {
    // selfroom stack still booting — show an honest note and retry shortly
    container.replaceChildren(h("p", { class: "muted empty-note", "data-testid": "contacts-starting" }, t("ctStarting")));
    const timer = setInterval(() => {
      if (Session.contacts && Session.selfroom) {
        clearInterval(timer);
        renderContactsTab(container);
      }
    }, 400);
    onDisconnect(container, () => clearInterval(timer));
    return;
  }

  const refresh = (): void => {
    if (container.isConnected) render();
  };

  // reactive: contacts/groups synced from another device re-render live
  const unsub = Session.selfroom.onStateChanged(() => {
    if (container.isConnected) render();
  });

  // countdown freshness for the pending section
  const countdown = setInterval(() => {
    if (container.isConnected) render();
  }, 60_000);

  // detach IMMEDIATELY when the view unmounts — nothing may outlive it
  onDisconnect(container, () => {
    unsub();
    clearInterval(countdown);
  });

  const render = (): void => {
    const state = svc.state;

    // never steal focus from the search box: remember focus + selection
    // across the re-render (the 60 s countdown re-render used to eat it)
    const prevSearch = container.querySelector<HTMLInputElement>('[data-testid="contacts-search"]');
    const hadFocus = prevSearch !== null && document.activeElement === prevSearch;
    const selStart = prevSearch?.selectionStart ?? null;
    const selEnd = prevSearch?.selectionEnd ?? null;

    const search = h("input", {
      type: "search",
      class: "text-input search-input",
      placeholder: t("ctSearchPh"),
      value: searchQuery,
      "data-testid": "contacts-search",
    }) as HTMLInputElement;
    search.addEventListener("input", () => {
      searchQuery = search.value;
      listBox.replaceChildren(contactList(state, refresh));
    });

    const listBox = h("div", {}, contactList(state, refresh));

    const actions = h(
      "div",
      { class: "btn-col" },
      h("button", { type: "button", class: "btn", "data-testid": "invite-create", onclick: () => openCreateInviteSheet(refresh) }, t("ctInvite")),
      h("button", { type: "button", class: "btn ghost", "data-testid": "invite-received", onclick: () => openReceivedSheet() }, t("ctReceived")),
    );

    container.replaceChildren(
      h("div", { class: "contacts-panel", "data-testid": "contacts-panel" },
        h("section", { class: "card" }, actions),
        noticesSection(),
        requestsSection(refresh),
        queuedSection(refresh),
        pendingSection(refresh),
        h("section", { class: "card" }, search, listBox),
        groupsSection(state, refresh),
      ),
    );

    if (hadFocus) {
      search.focus();
      if (selStart !== null && selEnd !== null) {
        try {
          search.setSelectionRange(selStart, selEnd);
        } catch {}
      }
    }
  };

  render();
  // the tab opened — look for accepted invites + public contact requests
  // (both throttled inside)
  void pollPendingInvites(refresh);
  void pollContactRequests(refresh);
}

static mirror of HEAD · about · clone: git clone https://cod-sursa.cautpartener.ro/cautpartener.git