Catalyst / admin/Bid-Sentinel 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Bid-Sentinel

public

Bid Scrape and Tracking Application with AI Capability

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

const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; // index = day_of_week

export default function Settings() {
  const { user } = useAuth();
  const isAdmin = user?.role === "admin";

  // One tab per section. Admin-only sections are added conditionally. Only the
  // active tab's panel is mounted, so each loads its own data when opened.
  const tabs = [];
  if (isAdmin) tabs.push({ id: "users", label: "Users & roles", el: <UsersPanel currentUserId={user?.id} /> });
  tabs.push({ id: "ai", label: "AI enhancement", el: <AiPanel isAdmin={isAdmin} /> });
  tabs.push({ id: "capability", label: "Capability & fit", el: <CapabilityPanel isAdmin={isAdmin} /> });
  tabs.push({ id: "portals", label: "Bid portals", el: <PortalsPanel isAdmin={isAdmin} /> });
  tabs.push({ id: "keywords", label: "Keywords", el: <KeywordsPanel isAdmin={isAdmin} /> });
  tabs.push({ id: "cpv", label: "CPV codes", el: <CpvPanel isAdmin={isAdmin} /> });
  tabs.push({ id: "tuneout", label: "Tune-out list", el: <TuneOutPanel isAdmin={isAdmin} /> });
  tabs.push({ id: "schedule", label: "Schedule", el: <SchedulePanel isAdmin={isAdmin} /> });
  if (isAdmin) tabs.push({ id: "audit", label: "Audit trail", el: <AuditPanel /> });

  const [active, setActive] = useState(tabs[0].id);
  const current = tabs.find((t) => t.id === active) || tabs[0];

  return (
    <div className="min-h-full">
      <header className="bg-brand text-white shadow">
        <div className="mx-auto flex max-w-5xl items-center justify-between px-6 py-3">
          <div className="flex items-center gap-3">
            <div className="rounded-lg bg-white px-2 py-1 shadow-sm">
              <img src={logo} alt="Bid Sentinel" className="h-9 w-auto object-contain" />
            </div>
            <h1 className="text-lg font-bold tracking-wide">Settings</h1>
          </div>
          <div className="flex items-center gap-3">
            <ThemeToggle />
            <Link to="/" className="rounded-md bg-white/10 px-3 py-1.5 text-sm hover:bg-white/20">
               Back to dashboard
            </Link>
          </div>
        </div>
      </header>

      <main className="mx-auto max-w-5xl px-6 py-6">
        {!isAdmin && (
          <div className="mb-4 rounded-lg bg-amber-50 px-4 py-3 text-sm text-amber-800">
            You are signed in as a standard user. Settings are read-only; an
            administrator can make changes.
          </div>
        )}

        {/* Tab bar */}
        <div className="mb-5 flex flex-wrap gap-1 border-b border-slate-200">
          {tabs.map((t) => (
            <button
              key={t.id}
              onClick={() => setActive(t.id)}
              className={`-mb-px border-b-2 px-3 py-2 text-sm font-medium transition ${
                t.id === active
                  ? "border-brand text-brand"
                  : "border-transparent text-slate-500 hover:border-slate-300 hover:text-slate-700"
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>

        {/* Active section */}
        {current.el}
      </main>
    </div>
  );
}

function Card({ title, subtitle, children }) {
  return (
    <section className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
      <h2 className="text-base font-semibold text-slate-800">{title}</h2>
      {subtitle && <p className="mb-4 mt-0.5 text-sm text-slate-500">{subtitle}</p>}
      {children}
    </section>
  );
}

/* ----------------------------- Audit trail -------------------------------- */
function AuditPanel() {
  const [entries, setEntries] = useState([]);
  const [loading, setLoading] = useState(true);

  function load() {
    setLoading(true);
    fetchAudit(200)
      .then(setEntries)
      .catch(() => {})
      .finally(() => setLoading(false));
  }
  useEffect(load, []);

  const fmt = (d) => new Date(d).toLocaleString("en-GB");
  const statusColor = (s) =>
    s == null ? "text-slate-400" : s >= 400 ? "text-red-600" : "text-green-600";

  return (
    <Card
      title="Audit trail"
      subtitle="Application activity — logins and every change (who, what, when). Most recent first."
    >
      <div className="mb-3">
        <button
          onClick={load}
          className="rounded-lg border border-slate-300 bg-white px-3 py-1.5 text-sm font-medium hover:bg-slate-50"
        >
          Refresh
        </button>
      </div>
      <div className="max-h-96 overflow-auto rounded-lg border border-slate-200">
        <table className="min-w-full text-sm">
          <thead className="sticky top-0 bg-slate-50">
            <tr className="text-left text-xs uppercase tracking-wide text-slate-400">
              <th className="px-3 py-2">When</th>
              <th className="px-3 py-2">Actor</th>
              <th className="px-3 py-2">Action</th>
              <th className="px-3 py-2">Status</th>
              <th className="px-3 py-2">IP</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {loading && (
              <tr>
                <td colSpan={5} className="px-3 py-4 text-slate-400">Loading</td>
              </tr>
            )}
            {!loading && entries.length === 0 && (
              <tr>
                <td colSpan={5} className="px-3 py-4 text-slate-400">No activity recorded yet.</td>
              </tr>
            )}
            {entries.map((e) => (
              <tr key={e.id}>
                <td className="whitespace-nowrap px-3 py-2 text-slate-500">{fmt(e.created_at)}</td>
                <td className="px-3 py-2 text-slate-700">{e.actor}</td>
                <td className="px-3 py-2 text-slate-700">
                  {e.action}
                  {e.detail && <span className="ml-1 text-xs text-slate-400">{e.detail}</span>}
                </td>
                <td className={`px-3 py-2 ${statusColor(e.status_code)}`}>{e.status_code ?? "—"}</td>
                <td className="px-3 py-2 text-slate-400">{e.ip || "—"}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </Card>
  );
}

/* --------------------------- Users (RBAC, admin) -------------------------- */
const ROLES = [
  ["standard", "Standard"],
  ["analyst", "Analyst"],
  ["admin", "Admin"],
];

function UsersPanel({ currentUserId }) {
  const [users, setUsers] = useState([]);
  const [fullName, setFullName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [role, setRole] = useState("standard");
  const [error, setError] = useState("");
  const [resetId, setResetId] = useState(null);
  const [resetPw, setResetPw] = useState("");

  async function load() {
    setUsers(await fetchUsers());
  }
  useEffect(() => {
    load().catch(() => {});
  }, []);

  async function add(e) {
    e.preventDefault();
    setError("");
    if (password.length < 8) {
      setError("Password must be at least 8 characters.");
      return;
    }
    try {
      await createUser({ email, full_name: fullName, password, role });
      setFullName("");
      setEmail("");
      setPassword("");
      setRole("standard");
      await load();
    } catch (err) {
      setError(err.response?.data?.detail || "Could not create user.");
    }
  }

  async function patch(u, changes) {
    try {
      const updated = await updateUser(u.id, changes);
      setUsers((prev) => prev.map((x) => (x.id === u.id ? updated : x)));
    } catch (err) {
      setError(err.response?.data?.detail || "Update failed.");
    }
  }

  async function remove(u) {
    if (!window.confirm(`Delete user ${u.email}?`)) return;
    try {
      await deleteUser(u.id);
      setUsers((prev) => prev.filter((x) => x.id !== u.id));
    } catch (err) {
      setError(err.response?.data?.detail || "Delete failed.");
    }
  }

  async function saveReset(u) {
    if (resetPw.length < 8) {
      setError("Password must be at least 8 characters.");
      return;
    }
    await patch(u, { password: resetPw });
    setResetId(null);
    setResetPw("");
  }

  return (
    <Card
      title="Users & roles"
      subtitle="Provision accounts and assign roles. Admins manage everything; standard users can view, filter, set bid status/outcome, and export."
    >
      <div className="mb-4 overflow-x-auto">
        <table className="min-w-full text-sm">
          <thead>
            <tr className="text-left text-xs uppercase tracking-wide text-slate-400">
              <th className="py-2 pr-4">User</th>
              <th className="py-2 pr-4">Role</th>
              <th className="py-2 pr-4">Status</th>
              <th className="py-2 pr-4"></th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-100">
            {users.map((u) => (
              <tr key={u.id}>
                <td className="py-2 pr-4">
                  <div className="font-medium text-slate-800">
                    {u.full_name || "—"}
                    {u.id === currentUserId && (
                      <span className="ml-1.5 text-xs font-normal text-slate-400">(you)</span>
                    )}
                  </div>
                  <div className="text-xs text-slate-500">{u.email}</div>
                  {resetId === u.id && (
                    <div className="mt-1 flex items-center gap-1">
                      <input
                        type="password"
                        value={resetPw}
                        onChange={(e) => setResetPw(e.target.value)}
                        placeholder="New password (min 8)"
                        className="rounded-md border border-slate-300 px-2 py-1 text-xs outline-none focus:border-brand"
                      />
                      <button
                        onClick={() => saveReset(u)}
                        className="rounded-md bg-brand px-2 py-1 text-xs text-white hover:bg-brand-dark"
                      >
                        Save
                      </button>
                      <button
                        onClick={() => {
                          setResetId(null);
                          setResetPw("");
                        }}
                        className="text-xs text-slate-400 hover:text-slate-600"
                      >
                        Cancel
                      </button>
                    </div>
                  )}
                </td>
                <td className="py-2 pr-4">
                  <select
                    value={u.role}
                    onChange={(e) => patch(u, { role: e.target.value })}
                    disabled={u.id === currentUserId}
                    title={u.id === currentUserId ? "You can't change your own role" : ""}
                    className="rounded-md border border-slate-300 px-2 py-1 text-sm outline-none focus:border-brand disabled:opacity-60"
                  >
                    {ROLES.map(([v, l]) => (
                      <option key={v} value={v}>
                        {l}
                      </option>
                    ))}
                  </select>
                </td>
                <td className="py-2 pr-4">
                  <button
                    onClick={() => patch(u, { is_active: !u.is_active })}
                    disabled={u.id === currentUserId}
                    className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                      u.is_active
                        ? "bg-green-50 text-green-700"
                        : "bg-slate-100 text-slate-500"
                    } disabled:opacity-60`}
                  >
                    {u.is_active ? "Active" : "Disabled"}
                  </button>
                </td>
                <td className="py-2 pr-4">
                  <div className="flex items-center gap-3 text-xs">
                    <button
                      onClick={() => {
                        setResetId(u.id);
                        setResetPw("");
                      }}
                      className="text-brand-light hover:underline"
                    >
                      Reset password
                    </button>
                    {u.id !== currentUserId && (
                      <button
                        onClick={() => remove(u)}
                        className="text-red-500 hover:underline"
                      >
                        Delete
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))}
            {users.length === 0 && (
              <tr>
                <td colSpan={4} className="py-3 text-sm text-slate-400">
                  Loading users
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">
        Add a new user
      </p>
      <form onSubmit={add} className="flex flex-wrap items-center gap-2">
        <input
          value={fullName}
          onChange={(e) => setFullName(e.target.value)}
          placeholder="Full name"
          className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
        />
        <input
          type="email"
          required
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="[email protected]"
          className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
        />
        <input
          type="password"
          required
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password (min 8)"
          className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
        />
        <select
          value={role}
          onChange={(e) => setRole(e.target.value)}
          className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
        >
          {ROLES.map(([v, l]) => (
            <option key={v} value={v}>
              {l}
            </option>
          ))}
        </select>
        <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
          Add user
        </button>
      </form>
      {error && <p className="mt-2 text-xs text-red-500">{error}</p>}
    </Card>
  );
}

/* ----------------------------- AI bolt-on --------------------------------- */
function AiPanel({ isAdmin }) {
  const [cfg, setCfg] = useState(null);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    fetchAiConfig().then(setCfg).catch(() => {});
  }, []);

  async function toggle() {
    if (!isAdmin || !cfg) return;
    setBusy(true);
    setError("");
    try {
      const updated = await setAiEnabled(!cfg.enabled);
      setCfg(updated);
    } catch (err) {
      setError(err.response?.data?.detail || "Could not change AI setting.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card
      title="AI enhancement (optional)"
      subtitle="When on, Bid Sentinel uses a low-cost Claude model to produce a richer summary, a reasoned fit score, and more accurate certifications and technical requirements. When off, it stays fully deterministic and offline."
    >
      {!cfg ? (
        <p className="text-sm text-slate-400">Loading</p>
      ) : (
        <>
          <div className="flex items-center justify-between gap-4">
            <div>
              <div className="flex items-center gap-2">
                <span className="font-medium text-slate-800">AI analysis</span>
                <span
                  className={`rounded px-1.5 py-0.5 text-xs ${
                    cfg.enabled ? "bg-green-100 text-green-700" : "bg-slate-100 text-slate-500"
                  }`}
                >
                  {cfg.enabled ? "On" : "Off"}
                </span>
                <span className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-500">
                  {cfg.model}
                </span>
              </div>
              <p className="mt-1 text-xs text-slate-500">
                {cfg.available
                  ? "API key configured. New scrapes use this setting; click “Recompute” below to apply it to existing opportunities."
                  : "No API key configured — set ANTHROPIC_API_KEY in the environment to enable."}
              </p>
            </div>
            <label className="relative inline-flex cursor-pointer items-center">
              <input
                type="checkbox"
                checked={cfg.enabled}
                disabled={!isAdmin || busy || !cfg.available}
                onChange={toggle}
                className="peer sr-only"
              />
              <div className="h-6 w-11 rounded-full bg-slate-300 transition peer-checked:bg-brand peer-disabled:opacity-50 after:absolute after:left-0.5 after:top-0.5 after:h-5 after:w-5 after:rounded-full after:bg-white after:transition after:content-[''] peer-checked:after:translate-x-5"></div>
            </label>
          </div>
          {error && <p className="mt-2 text-xs text-red-500">{error}</p>}
        </>
      )}
    </Card>
  );
}

/* --------------------- Capability profile & fit (no AI) ------------------- */
function CapabilityPanel({ isAdmin }) {
  const [terms, setTerms] = useState([]);
  const [certs, setCerts] = useState([]);
  const [input, setInput] = useState("");
  const [suggested, setSuggested] = useState([]);
  const [picked, setPicked] = useState(() => new Set());
  const [uploadInfo, setUploadInfo] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");
  const [accreditations, setAccreditations] = useState([]);
  const [accInput, setAccInput] = useState("");

  async function load() {
    const data = await fetchCapabilities();
    setTerms(data.terms);
  }
  useEffect(() => {
    load().catch(() => {});
    fetchCertLexicon().then(setCerts).catch(() => {});
    fetchAccreditations().then(setAccreditations).catch(() => {});
  }, []);

  async function addAcc(e) {
    e.preventDefault();
    const name = accInput.trim();
    if (!name) return;
    try {
      const created = await addAccreditation(name);
      setAccreditations((prev) => [...prev, created]);
      setAccInput("");
    } catch (err) {
      if (err.response?.status !== 409) setError(err.response?.data?.detail || "Could not add");
    }
  }
  async function removeAcc(id) {
    await deleteAccreditation(id);
    setAccreditations((prev) => prev.filter((a) => a.id !== id));
  }

  async function addTerm(term) {
    try {
      const created = await addCapability(term);
      setTerms((prev) => [...prev, created]);
      return created;
    } catch (err) {
      if (err.response?.status !== 409) setError(err.response?.data?.detail || "Could not add term");
      return null;
    }
  }

  async function handleAddTyped(e) {
    e.preventDefault();
    setError("");
    const t = input.trim();
    if (!t) return;
    await addTerm(t);
    setInput("");
  }

  async function remove(id) {
    await deleteCapability(id);
    setTerms((prev) => prev.filter((t) => t.id !== id));
  }

  async function handleUpload(e) {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    setError("");
    setBusy(true);
    setUploadInfo("");
    try {
      const res = await uploadCapabilityDoc(file);
      setSuggested(res.suggested);
      setPicked(new Set()); // user ticks the ones they want
      setUploadInfo(
        `Generated ${res.suggested.length} suggestion(s) from ${res.filename} ` +
          `(${res.extracted_chars.toLocaleString()} chars) via ${res.generated_by}` +
          (res.detected_certs.length ? `. Certs seen: ${res.detected_certs.join(", ")}` : "") +
          "."
      );
    } catch (err) {
      setError(err.response?.data?.detail || "Upload failed.");
    } finally {
      setBusy(false);
    }
  }

  function togglePick(term) {
    setPicked((prev) => {
      const next = new Set(prev);
      next.has(term) ? next.delete(term) : next.add(term);
      return next;
    });
  }

  async function confirmSuggestions() {
    for (const term of suggested) {
      if (picked.has(term)) await addTerm(term);
    }
    setSuggested([]);
    setPicked(new Set());
    setUploadInfo("");
  }

  async function handleRecompute() {
    setBusy(true);
    setNotice("");
    try {
      const res = await recomputeAnalysis();
      setNotice(res.message);
    } catch (err) {
      setNotice(err.response?.data?.detail || "Recompute failed.");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card
      title="Capability profile & fit"
      subtitle="Define the services you offer. These drive each opportunity's Fit % — by keyword overlap (deterministic), or, when the AI enhancement is on, as the capabilities the model scores against."
    >
      {/* Current profile */}
      <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
        Your capability terms
      </p>
      <div className="mb-3 flex flex-wrap gap-1.5">
        {terms.length === 0 && (
          <span className="text-xs text-slate-400">
            None yet  fit is shown once you add terms (or upload a document below).
          </span>
        )}
        {terms.map((t) => (
          <span
            key={t.id}
            className="flex items-center gap-1.5 rounded-full bg-brand/10 px-2.5 py-1 text-xs text-brand"
          >
            {t.term}
            {isAdmin && (
              <button onClick={() => remove(t.id)} className="text-brand/60 hover:text-red-500" title="Remove">
                
              </button>
            )}
          </span>
        ))}
      </div>

      {isAdmin && (
        <>
          <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
            Add a term manually
          </p>
          <form onSubmit={handleAddTyped} className="mb-4 flex gap-2">
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="e.g. Penetration Testing"
              className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
            />
            <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
              Add
            </button>
          </form>

          {/* Document upload */}
          <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
            Generate terms from a document
          </p>
          <div className="mb-3 rounded-lg border border-slate-200 p-4">
            <p className="mb-1 text-sm font-medium text-slate-700">
              Upload a service-overview document
            </p>
            <p className="mb-2 text-xs text-slate-500">
              PDF, DOCX, or TXT. Bid Sentinel generates capability terms from its
              content  you tick the ones to keep. Generated locally by keyword
              extraction, or by AI when the AI enhancement is enabled.
            </p>
            <input
              type="file"
              accept=".pdf,.docx,.txt"
              onChange={handleUpload}
              disabled={busy}
              className="text-sm"
            />
            {uploadInfo && <p className="mt-2 text-xs text-slate-500">{uploadInfo}</p>}

            {suggested.length > 0 && (
              <div className="mt-3">
                <div className="mb-1 flex items-center gap-3">
                  <p className="text-xs font-semibold uppercase tracking-wide text-slate-400">
                    Generated terms  tick to add
                  </p>
                  <button
                    type="button"
                    onClick={() => setPicked(new Set(suggested))}
                    className="text-xs text-brand-light hover:underline"
                  >
                    Select all
                  </button>
                  <button
                    type="button"
                    onClick={() => setPicked(new Set())}
                    className="text-xs text-slate-400 hover:underline"
                  >
                    Clear
                  </button>
                </div>
                <div className="mb-2 flex flex-wrap gap-2">
                  {suggested.map((term) => (
                    <label
                      key={term}
                      className={`flex cursor-pointer items-center gap-1.5 rounded-md border px-2 py-1 text-xs ${
                        picked.has(term) ? "border-brand bg-brand/5 text-brand" : "border-slate-300 text-slate-600"
                      }`}
                    >
                      <input
                        type="checkbox"
                        checked={picked.has(term)}
                        onChange={() => togglePick(term)}
                        className="h-3 w-3"
                      />
                      {term}
                    </label>
                  ))}
                </div>
                <button
                  onClick={confirmSuggestions}
                  className="rounded-lg bg-brand px-3 py-1.5 text-sm font-semibold text-white hover:bg-brand-dark"
                >
                  Add selected
                </button>
              </div>
            )}
          </div>

          <div className="mb-3 flex items-center gap-3">
            <button
              onClick={handleRecompute}
              disabled={busy}
              className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50 disabled:opacity-60"
            >
              {busy ? "Working…" : "Recompute fit & certs for all opportunities"}
            </button>
            <span className="text-xs text-slate-400">
              Run after changing the profile (new opportunities are scored automatically).
            </span>
          </div>
          {notice && <p className="mb-2 text-xs text-blue-600">{notice}</p>}
          {error && <p className="mb-2 text-xs text-red-500">{error}</p>}
        </>
      )}

      {/* Accreditations held (powers cert-gap analysis in Intelligence) */}
      <p className="mb-1 mt-4 text-xs font-semibold uppercase tracking-wide text-slate-400">
        Accreditations you hold
      </p>
      <p className="mb-2 text-xs text-slate-500">
        Used by the Intelligence tab to flag which required certifications you already hold vs gaps.
      </p>
      <div className="mb-2 flex flex-wrap gap-1.5">
        {accreditations.length === 0 && <span className="text-xs text-slate-400">None listed yet.</span>}
        {accreditations.map((a) => (
          <span key={a.id} className="flex items-center gap-1.5 rounded-full bg-green-50 px-2.5 py-1 text-xs text-green-700">
            {a.name}
            {isAdmin && (
              <button onClick={() => removeAcc(a.id)} className="text-green-600/60 hover:text-red-500" title="Remove">
                
              </button>
            )}
          </span>
        ))}
      </div>
      {isAdmin && (
        <form onSubmit={addAcc} className="mb-4 flex gap-2">
          <input
            value={accInput}
            onChange={(e) => setAccInput(e.target.value)}
            placeholder="e.g. Cyber Essentials Plus"
            className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
          />
          <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
            Add
          </button>
        </form>
      )}

      {/* Cert lexicon (informational) */}
      <p className="mb-1 mt-2 text-xs font-semibold uppercase tracking-wide text-slate-400">
        Certifications &amp; accreditations watched ({certs.length})
      </p>
      <div className="flex flex-wrap gap-1.5">
        {certs.map((c) => (
          <span key={c} className="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600">
            {c}
          </span>
        ))}
      </div>
    </Card>
  );
}

/* -------------------------------- Portals -------------------------------- */
function PortalsPanel({ isAdmin }) {
  const [portals, setPortals] = useState([]);
  const [busy, setBusy] = useState(null);
  const [name, setName] = useState("");
  const [url, setUrl] = useState("");
  const [scope, setScope] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    fetchPortals().then(setPortals).catch(() => {});
  }, []);

  async function toggle(p) {
    if (!isAdmin) return;
    setBusy(p.key);
    try {
      const updated = await setPortalEnabled(p.key, !p.enabled);
      setPortals((prev) => prev.map((x) => (x.key === p.key ? updated : x)));
    } finally {
      setBusy(null);
    }
  }

  async function handleAdd(e) {
    e.preventDefault();
    setError("");
    try {
      const created = await addPortal({ name, url, scope });
      setPortals((prev) => [...prev, created]);
      setName("");
      setUrl("");
      setScope("");
    } catch (err) {
      setError(err.response?.data?.detail || "Could not add portal.");
    }
  }

  async function remove(p) {
    if (!window.confirm(`Delete custom portal "${p.name}"?`)) return;
    try {
      await deletePortal(p.key);
      setPortals((prev) => prev.filter((x) => x.key !== p.key));
    } catch (err) {
      setError(err.response?.data?.detail || "Could not delete portal.");
    }
  }

  return (
    <Card
      title="Bid Portals"
      subtitle="All portals are checked by default. Untick any you want Bid Sentinel to skip, or add your own below."
    >
      <ul className="divide-y divide-slate-100">
        {portals.map((p) => (
          <li key={p.key} className="flex items-start justify-between gap-4 py-3">
            <div>
              <div className="flex items-center gap-2">
                <span className="font-medium text-slate-800">{p.name}</span>
                {p.live ? (
                  <span className="rounded bg-green-100 px-1.5 py-0.5 text-xs text-green-700">
                    Live
                  </span>
                ) : (
                  <span className="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-500">
                    Registered
                  </span>
                )}
                {p.custom && (
                  <span className="rounded bg-brand/10 px-1.5 py-0.5 text-xs text-brand">Custom</span>
                )}
              </div>
              {p.scope && <p className="mt-0.5 text-xs text-slate-500">{p.scope}</p>}
              <a href={p.url} target="_blank" rel="noreferrer" className="text-xs text-brand-light hover:underline">
                {p.url}
              </a>
            </div>
            <div className="flex items-center gap-3">
              {isAdmin && p.custom && (
                <button
                  onClick={() => remove(p)}
                  className="text-xs text-red-500 hover:underline"
                  title="Delete this custom portal"
                >
                  Delete
                </button>
              )}
              <label className="relative inline-flex cursor-pointer items-center">
                <input
                  type="checkbox"
                  checked={p.enabled}
                  disabled={!isAdmin || busy === p.key}
                  onChange={() => toggle(p)}
                  className="peer sr-only"
                />
                <div className="h-6 w-11 rounded-full bg-slate-300 transition peer-checked:bg-brand peer-disabled:opacity-50 after:absolute after:left-0.5 after:top-0.5 after:h-5 after:w-5 after:rounded-full after:bg-white after:transition after:content-[''] peer-checked:after:translate-x-5"></div>
              </label>
            </div>
          </li>
        ))}
        {portals.length === 0 && <li className="py-3 text-sm text-slate-400">Loading portals</li>}
      </ul>

      {isAdmin && (
        <div className="mt-4 rounded-lg border border-slate-200 p-4">
          <p className="mb-1 text-sm font-medium text-slate-700">Add a portal</p>
          <p className="mb-3 text-xs text-slate-500">
            Registers a portal so it appears here and in the schedule. Custom portals
            have no automated scraper yet (marked Registered), but you can enable,
            schedule, and later wire up a scraper for them.
          </p>
          <form onSubmit={handleAdd} className="flex flex-wrap items-center gap-2">
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
              placeholder="Portal name"
              className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
            />
            <input
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              required
              type="url"
              placeholder="https://portal.example.gov.uk"
              className="min-w-[220px] flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
            />
            <input
              value={scope}
              onChange={(e) => setScope(e.target.value)}
              placeholder="Scope (optional)"
              className="min-w-[180px] flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand"
            />
            <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
              Add portal
            </button>
          </form>
          {error && <p className="mt-2 text-xs text-red-500">{error}</p>}
        </div>
      )}
    </Card>
  );
}

/* ------------------------------- Keywords -------------------------------- */
function KeywordsPanel({ isAdmin }) {
  const [builtin, setBuiltin] = useState([]);
  const [custom, setCustom] = useState([]);
  const [input, setInput] = useState("");
  const [error, setError] = useState("");

  async function load() {
    const data = await fetchKeywords();
    setBuiltin(data.builtin);
    setCustom(data.custom);
  }
  useEffect(() => {
    load().catch(() => {});
  }, []);

  async function add(e) {
    e.preventDefault();
    setError("");
    const kw = input.trim();
    if (!kw) return;
    try {
      const created = await addKeyword(kw);
      setCustom((prev) => [...prev, created]);
      setInput("");
    } catch (err) {
      setError(err.response?.data?.detail || "Could not add keyword");
    }
  }

  async function remove(id) {
    await deleteKeyword(id);
    setCustom((prev) => prev.filter((k) => k.id !== id));
  }

  return (
    <Card
      title="Keywords"
      subtitle="Bid Sentinel always searches its built-in cyber-security terms. Optionally add your own."
    >
      <div className="mb-3">
        <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
          Built-in (always on)
        </p>
        <div className="flex flex-wrap gap-1.5">
          {builtin.map((k) => (
            <span key={k} className="rounded-full bg-brand/10 px-2.5 py-1 text-xs text-brand">
              {k}
            </span>
          ))}
        </div>
      </div>

      <div>
        <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
          Your custom keywords (optional)
        </p>
        <div className="mb-2 flex flex-wrap gap-1.5">
          {custom.length === 0 && <span className="text-xs text-slate-400">None added yet.</span>}
          {custom.map((k) => (
            <span
              key={k.id}
              className="flex items-center gap-1.5 rounded-full bg-slate-100 px-2.5 py-1 text-xs text-slate-700"
            >
              {k.keyword}
              {isAdmin && (
                <button onClick={() => remove(k.id)} className="text-slate-400 hover:text-red-500" title="Remove">
                  
                </button>
              )}
            </span>
          ))}
        </div>
        {isAdmin && (
          <form onSubmit={add} className="flex gap-2">
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="e.g. Penetration Testing"
              className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
            />
            <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
              Add
            </button>
          </form>
        )}
        {error && <p className="mt-1 text-xs text-red-500">{error}</p>}
      </div>
    </Card>
  );
}

/* ------------------------------- CPV codes ------------------------------- */
function CpvPanel({ isAdmin }) {
  const [codes, setCodes] = useState([]);
  const [code, setCode] = useState("");
  const [description, setDescription] = useState("");
  const [error, setError] = useState("");
  const [strict, setStrict] = useState(false);

  async function load() {
    setCodes(await fetchCpvCodes());
  }
  useEffect(() => {
    load().catch(() => {});
    fetchCpvStrict()
      .then((s) => setStrict(Boolean(s.strict)))
      .catch(() => {});
  }, []);

  async function toggleStrict() {
    if (!isAdmin) return;
    try {
      const res = await setCpvStrict(!strict);
      setStrict(Boolean(res.strict));
    } catch (err) {
      setError(err.response?.data?.detail || "Could not change CPV mode.");
    }
  }

  async function add(e) {
    e.preventDefault();
    setError("");
    if (!code.trim()) return;
    try {
      const created = await addCpvCode({ code: code.trim(), description: description.trim() });
      setCodes((prev) => [...prev, created]);
      setCode("");
      setDescription("");
    } catch (err) {
      setError(err.response?.data?.detail || "Could not add CPV code.");
    }
  }

  async function toggle(c) {
    if (!isAdmin) return;
    try {
      const updated = await setCpvEnabled(c.id, !c.enabled);
      setCodes((prev) => prev.map((x) => (x.id === c.id ? updated : x)));
    } catch (err) {
      setError(err.response?.data?.detail || "Could not update CPV code.");
    }
  }

  async function remove(id) {
    await deleteCpvCode(id);
    setCodes((prev) => prev.filter((c) => c.id !== id));
  }

  const activeCount = codes.filter((c) => c.enabled).length;

  return (
    <Card
      title="CPV codes"
      subtitle="Common Procurement Vocabulary codes that NARROW the scrape. When any are enabled, an opportunity must match a keyword AND one of these CPV codes to be kept. Toggle a code off to exclude it without deleting it."
    >
      {/* Matching mode */}
      <div className="mb-4 flex items-start justify-between gap-4 rounded-lg border border-slate-200 bg-slate-50 p-3">
        <div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium text-slate-800">CPV matching mode</span>
            <span
              className={`rounded px-1.5 py-0.5 text-xs ${
                strict ? "bg-amber-100 text-amber-700" : "bg-green-100 text-green-700"
              }`}
            >
              {strict ? "Strict" : "Lenient (recommended)"}
            </span>
          </div>
          <p className="mt-1 text-xs text-slate-500">
            {strict
              ? "Strict: every opportunity must match one of your CPV codes. Notices from sources with no CPV data (most HTML portals) are excluded."
              : "Lenient: CPV codes only narrow notices that actually declare a CPV classification. Notices with no CPV data are judged on keywords alone, so you don't lose opportunities from portals that don't publish CPV codes."}
          </p>
        </div>
        <label className="relative inline-flex cursor-pointer items-center pt-1">
          <input
            type="checkbox"
            checked={strict}
            disabled={!isAdmin}
            onChange={toggleStrict}
            className="peer sr-only"
          />
          <div className="h-6 w-11 rounded-full bg-slate-300 transition peer-checked:bg-amber-500 peer-disabled:opacity-50 after:absolute after:left-0.5 after:top-0.5 after:h-5 after:w-5 after:rounded-full after:bg-white after:transition after:content-[''] peer-checked:after:translate-x-5"></div>
        </label>
      </div>

      <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
        Your CPV codes ({activeCount} of {codes.length} active)
      </p>
      <div className="mb-4 overflow-x-auto">
        {codes.length === 0 ? (
          <p className="text-xs text-slate-400">
            None added yet. Add codes such as 72500000 (Computer-related services)
            or 79714000 (Surveillance services) to narrow the scrape.
          </p>
        ) : (
          <table className="min-w-full text-sm">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wide text-slate-400">
                <th className="py-2 pr-4">Active</th>
                <th className="py-2 pr-4">Code</th>
                <th className="py-2 pr-4">Description</th>
                <th className="py-2 pr-4"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {codes.map((c) => (
                <tr key={c.id} className={c.enabled ? "" : "opacity-50"}>
                  <td className="py-2 pr-4">
                    <label className="relative inline-flex cursor-pointer items-center">
                      <input
                        type="checkbox"
                        checked={c.enabled}
                        disabled={!isAdmin}
                        onChange={() => toggle(c)}
                        className="peer sr-only"
                      />
                      <div className="h-5 w-9 rounded-full bg-slate-300 transition peer-checked:bg-brand peer-disabled:opacity-50 after:absolute after:left-0.5 after:top-0.5 after:h-4 after:w-4 after:rounded-full after:bg-white after:transition after:content-[''] peer-checked:after:translate-x-4"></div>
                    </label>
                  </td>
                  <td className="py-2 pr-4 font-mono text-slate-800">{c.code}</td>
                  <td className="py-2 pr-4 text-slate-600">{c.description || "—"}</td>
                  <td className="py-2 pr-4">
                    {isAdmin && (
                      <button
                        onClick={() => remove(c.id)}
                        className="text-xs text-red-500 hover:underline"
                      >
                        Remove
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {isAdmin && (
        <>
          <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
            Add a CPV code
          </p>
          <form onSubmit={add} className="flex flex-wrap items-center gap-2">
            <input
              value={code}
              onChange={(e) => setCode(e.target.value)}
              required
              placeholder="Code, e.g. 72500000"
              className="w-40 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
            />
            <input
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Description, e.g. Computer-related services"
              className="min-w-[220px] flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
            />
            <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
              Add
            </button>
          </form>
          {error && <p className="mt-2 text-xs text-red-500">{error}</p>}
          <p className="mt-2 text-xs text-slate-400">
            The check-digit suffix is optional (72500000 and 72500000-0 are treated
            the same). Codes and descriptions apply on the next scrape.
          </p>
        </>
      )}
    </Card>
  );
}

/* ------------------------------ Tune-out list ---------------------------- */
function TuneOutPanel({ isAdmin }) {
  const [terms, setTerms] = useState([]);
  const [input, setInput] = useState("");
  const [error, setError] = useState("");
  const [notice, setNotice] = useState("");

  async function load() {
    setTerms(await fetchTuneOuts());
  }
  useEffect(() => {
    load().catch(() => {});
  }, []);

  async function add(e) {
    e.preventDefault();
    setError("");
    setNotice("");
    const term = input.trim();
    if (!term) return;
    try {
      const res = await addTuneOut(term);
      setTerms((prev) => [...prev, res.term]);
      setInput("");
      setNotice(
        `Added “${term}”. Removed ${res.removed} matching non-cyber ` +
          `opportunit${res.removed === 1 ? "y" : "ies"}.`
      );
    } catch (err) {
      setError(err.response?.data?.detail || "Could not add tune-out term.");
    }
  }

  async function remove(id) {
    await deleteTuneOut(id);
    setTerms((prev) => prev.filter((t) => t.id !== id));
  }

  return (
    <Card
      title="Tune-out list"
      subtitle="Words or phrases that mark an opportunity TYPE as irrelevant. Matching opportunities are hidden and won't return on future scrapes. Anything Cyber Security related is always kept, whatever is on this list."
    >
      <div className="mb-3 rounded-lg bg-green-50 px-3 py-2 text-xs text-green-800">
        Guardrail: an opportunity is only tuned out when it matches a term here
        <b> and</b> has no cyber-security signal. Genuine cyber opportunities are
        never suppressed.
      </div>

      <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
        Tuned-out terms ({terms.length})
      </p>
      <div className="mb-4 flex flex-wrap gap-1.5">
        {terms.length === 0 && (
          <span className="text-xs text-slate-400">
            None yet  use the 🔕 Tune out button on a dashboard row, or add one below.
          </span>
        )}
        {terms.map((t) => (
          <span
            key={t.id}
            className="flex items-center gap-1.5 rounded-full bg-amber-50 px-2.5 py-1 text-xs text-amber-700"
          >
            {t.term}
            {isAdmin && (
              <button
                onClick={() => remove(t.id)}
                className="text-amber-600/70 hover:text-red-500"
                title="Remove (lets this type back in on the next scrape)"
              >
                
              </button>
            )}
          </span>
        ))}
      </div>

      {isAdmin && (
        <>
          <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-slate-400">
            Add a tune-out term
          </p>
          <form onSubmit={add} className="flex gap-2">
            <input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="e.g. catering, grounds maintenance, printer supplies"
              className="flex-1 rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand focus:ring-2 focus:ring-brand/20"
            />
            <button className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
              Add
            </button>
          </form>
          {notice && <p className="mt-2 text-xs text-blue-600">{notice}</p>}
          {error && <p className="mt-2 text-xs text-red-500">{error}</p>}
        </>
      )}
    </Card>
  );
}

/* ------------------------------- Schedule -------------------------------- */
function SchedulePanel({ isAdmin }) {
  const [info, setInfo] = useState({ timezone: "", slots: [], next_run: null });
  const [days, setDays] = useState([]); // selected day indices
  const [times, setTimes] = useState(["09:00"]);
  const [error, setError] = useState("");

  async function load() {
    setInfo(await fetchSchedule());
  }
  useEffect(() => {
    load().catch(() => {});
  }, []);

  function toggleDay(i) {
    setDays((prev) => (prev.includes(i) ? prev.filter((d) => d !== i) : [...prev, i]));
  }
  function updateTime(idx, val) {
    setTimes((prev) => prev.map((t, i) => (i === idx ? val : t)));
  }
  function addTimeField() {
    setTimes((prev) => [...prev, "12:00"]);
  }
  function removeTimeField(idx) {
    setTimes((prev) => (prev.length === 1 ? prev : prev.filter((_, i) => i !== idx)));
  }

  async function addSlots() {
    setError("");
    if (days.length === 0 || times.length === 0) {
      setError("Pick at least one day and one time.");
      return;
    }
    try {
      await addScheduleSlots(days, times);
      setDays([]);
      setTimes(["09:00"]);
      await load();
    } catch (err) {
      setError(err.response?.data?.detail || "Could not save schedule.");
    }
  }

  async function toggleSlot(slot) {
    await toggleScheduleSlot(slot.id, !slot.enabled);
    await load();
  }
  async function removeSlot(id) {
    await deleteScheduleSlot(id);
    await load();
  }

  const fmt = (s) => `${DAYS[s.day_of_week]} ${String(s.hour).padStart(2, "0")}:${String(s.minute).padStart(2, "0")}`;

  return (
    <Card
      title="Scrape Schedule"
      subtitle={`Run Bid Sentinel automatically on multiple days and times (${info.timezone || "local"} time). If no slots are set, an interval fallback is used.`}
    >
      {info.next_run && (
        <p className="mb-3 text-sm text-slate-600">
          Next run: <span className="font-medium">{new Date(info.next_run).toLocaleString("en-GB")}</span>
        </p>
      )}

      {/* Existing slots */}
      <div className="mb-4 flex flex-wrap gap-2">
        {info.slots.length === 0 && (
          <span className="text-sm text-slate-400">No schedule set  using interval fallback.</span>
        )}
        {info.slots.map((s) => (
          <span
            key={s.id}
            className={`flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm ${
              s.enabled ? "border-brand/30 bg-brand/5 text-brand" : "border-slate-200 bg-slate-50 text-slate-400"
            }`}
          >
            {fmt(s)}
            {isAdmin && (
              <>
                <button onClick={() => toggleSlot(s)} title={s.enabled ? "Pause" : "Resume"} className="hover:opacity-70">
                  {s.enabled ? "⏸" : "▶"}
                </button>
                <button onClick={() => removeSlot(s.id)} title="Delete" className="text-slate-400 hover:text-red-500">
                  
                </button>
              </>
            )}
          </span>
        ))}
      </div>

      {/* Builder */}
      {isAdmin && (
        <div className="rounded-lg border border-slate-200 p-4">
          <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">Days</p>
          <div className="mb-4 flex flex-wrap gap-2">
            {DAYS.map((label, i) => (
              <button
                key={label}
                type="button"
                onClick={() => toggleDay(i)}
                className={`rounded-md border px-3 py-1.5 text-sm font-medium transition ${
                  days.includes(i)
                    ? "border-brand bg-brand text-white"
                    : "border-slate-300 bg-white text-slate-600 hover:bg-slate-50"
                }`}
              >
                {label}
              </button>
            ))}
          </div>

          <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-slate-400">Times</p>
          <div className="mb-4 flex flex-wrap items-center gap-2">
            {times.map((t, idx) => (
              <span key={idx} className="flex items-center gap-1">
                <input
                  type="time"
                  value={t}
                  onChange={(e) => updateTime(idx, e.target.value)}
                  className="rounded-md border border-slate-300 px-2 py-1.5 text-sm outline-none focus:border-brand"
                />
                {times.length > 1 && (
                  <button onClick={() => removeTimeField(idx)} className="text-slate-400 hover:text-red-500" title="Remove time">
                    
                  </button>
                )}
              </span>
            ))}
            <button onClick={addTimeField} type="button" className="rounded-md border border-dashed border-slate-300 px-3 py-1.5 text-sm text-slate-500 hover:bg-slate-50">
              + Add time
            </button>
          </div>

          <button onClick={addSlots} className="rounded-lg bg-brand px-4 py-2 text-sm font-semibold text-white hover:bg-brand-dark">
            Add to schedule
          </button>
          {error && <p className="mt-2 text-xs text-red-500">{error}</p>}
          <p className="mt-2 text-xs text-slate-400">
            Selecting multiple days and times creates a slot for each combination
            (e.g. Mon/Wed at 09:00 &amp; 17:00  4 slots).
          </p>
        </div>
      )}
    </Card>
  );
}