All files / src/app/onboarding page.tsx

97.29% Statements 144/148
85.47% Branches 153/179
94.87% Functions 37/39
97.79% Lines 133/136

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 10553x                                                                                                                                           3x                                           3x                                                                                 3x                                                                         3x                                               221x     221x 221x 206x         200x       165x   162x 159x   159x       159x 36x       15x       15x                                     99x 99x                   99x 3x                 96x 1x                 95x 72x         23x 14x         9x                     21x 21x 21x 21x         21x     20x         21x   21x                                                                 21x     105x                                                                                         21x                                                               9x 9x 9x 9x   9x 2x 2x 2x 2x       2x       2x 1x   1x   1x 1x 1x       9x                                                                       2x                                                         99x 99x   99x 99x   99x     99x 99x   99x                     20x                                                                                                                                                                                                                                                                     609x 609x   609x       5x                                                   12x           64x                                                       1108x 1108x 1108x 1108x 1108x 1108x 1108x     1108x   1108x 1108x 1108x       1108x 1108x 1108x         1108x 113x         1108x 94x 94x 88x   88x 88x   1x     1108x 83x                 1108x 1108x 96x 12x 12x     1108x 16x 16x 16x 16x   16x 16x                     12x 3x     3x     9x 9x 2x               9x 9x   5x 5x       1108x                                                               113x       1x                                                                       1x 1x 1x 1x 1x                                                                     165x                                 156x                           3240x                         1x                                                                                               84x            
"use client";
 
import { fetchApi } from "@/lib/api";
import { IS_STATIC } from "@/lib/static-export";
import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import {
  AlertTriangle,
  Building2,
  CheckCircle2,
  ChevronDown,
  ChevronRight,
  Circle,
  Clock,
  ExternalLink,
  FileText,
  Loader2,
  Mail,
  MapPin,
  ShieldCheck,
  Trash2,
  UserPlus,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import type { VpaSummary } from "@/lib/provisioning";
import { useT } from "@/lib/i18n/translate";
import { useDemoPersona } from "@/lib/use-demo-persona";
import { useTabSession } from "@/lib/use-tab-session";
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface ParticipantProfile {
  dataspaceProfileId?: string;
  participantContextId: string;
  tenantId?: string;
  identifier?: string;
  did?: string;
  state?: string;
}
 
interface Tenant {
  id: string;
  version: number;
  properties: {
    displayName?: string;
    role?: string;
    ehdsParticipantType?: string;
    organization?: string;
    /** Set on a context registered through this page; only those can be removed. */
    registeredAt?: string;
  };
  participantProfiles: ParticipantProfile[];
  /** false for a registration nothing could provision (issue #203). */
  provisioned?: boolean;
  demoReason?: string;
  /** Every provisioning activity still pending long past creation (#203). */
  provisioningStalled?: boolean;
  stalledReason?: string;
  /** An agent reported an error and the profile was rolled back. */
  provisioningFailed?: boolean;
  failedReason?: string;
  /** Every provisioning activity completed. */
  provisioningComplete?: boolean;
  vpaSummary?: VpaSummary;
}
 
type RegistrationStep = "form" | "submitting" | "done";
 
/** How often the list is re-read while a registration is provisioning. */
const POLL_MS = 5_000;
 
type TenantStatus =
  | "active"
  | "provisioning"
  | "stalled"
  | "failed"
  | "pending"
  | "not-provisioned";
 
// ---------------------------------------------------------------------------
// Fictive contact database for demo participants
// ---------------------------------------------------------------------------
const CONTACT_DB: Record<
  string,
  {
    address: string;
    email: string;
    website: string;
    dpoName: string;
    dpoEmail: string;
  }
> = {
  "AlphaKlinik Berlin": {
    address: "Gesundheitsplatz 1, 10117 Berlin, Germany",
    email: "forschung@alpha-klinik.de",
    website: "https://www.alpha-klinik.de",
    dpoName: "Prof. Dr. Klaus Weber",
    dpoEmail: "datenschutz@alpha-klinik.de",
  },
  "PharmaCo Research AG": {
    address: "Industriestraße 42, 51373 Leverkusen, Germany",
    email: "clinical-research@pharmaco.de",
    website: "https://www.pharmaco.de/research",
    dpoName: "Dr. Sandra Koch",
    dpoEmail: "data-protection@pharmaco.de",
  },
  "MedReg DE": {
    address: "Regulierungsallee 3, 53175 Bonn, Germany",
    email: "info@medreg.de",
    website: "https://www.medreg.de",
    dpoName: "Dr. Frank Bauer",
    dpoEmail: "datenschutz@medreg.de",
  },
  "Limburg Medical Centre": {
    address: "Postbus 5500, 6202 AZ Maastricht, Netherlands",
    email: "research@lmc.nl",
    website: "https://www.lmc.nl",
    dpoName: "Dr. Jan de Vries",
    dpoEmail: "privacy@lmc.nl",
  },
  "Institut de Recherche Santé": {
    address: "12 Rue de la Santé, 75014 Paris, France",
    email: "contact@irs.fr",
    website: "https://www.irs.fr",
    dpoName: "Dr. Marie Dupont",
    dpoEmail: "dpo@irs.fr",
  },
};
 
// ---------------------------------------------------------------------------
// EHDS + contractual requirements content
// ---------------------------------------------------------------------------
const REQUIREMENTS = [
  {
    category: "EHDS Regulation (EU 2025/327): secondary use",
    items: [
      "Art. 60(1): Data holders make health data available for approved secondary-use purposes on request of the HDAB.",
      "Purpose limitation: only approved uses (research, policy analysis, education, statistics).",
      "Pseudonymisation required before transfer (Art. 66); re-identification is prohibited (Art. 61(3)).",
      "Data must be provided via an accredited Secure Processing Environment (SPE) listed in the HealthDCAT-AP catalogue.",
      "Interoperability: FHIR R4 and OMOP CDM formats required for clinical data exchange.",
      "Audit log retention for 10 years (Art. 34 accountability).",
    ],
  },
  {
    category: "Contractual / NDA Requirements",
    items: [
      "Data Access Agreement (DAA) signed between data user and HDAB before any transfer.",
      "Data Processing Agreement (DPA): GDPR Art. 28 compliant, listing all sub-processors.",
      "Mutual Non-Disclosure Agreement (NDA) covering proprietary algorithms, intermediate results, and derived datasets.",
      "Sub-processor disclosure if third-party cloud infrastructure is involved in processing.",
      "Breach notification procedure within 72 hours per GDPR Art. 33.",
    ],
  },
  {
    category: "Technical Dataspace Prerequisites (EDC-V / DCP)",
    items: [
      "Valid did:web DID registered with IdentityHub and endorsed by HDAB VC credential.",
      "Signed EDC-V connector policies: dataspace membership, EHDS-purpose, data-usage constraints.",
      "Encrypted transfer channel (AES-256-GCM) via EDC Dataspace Protocol (DCP).",
      "NATS event subscription for real-time audit events and contract negotiation callbacks.",
      "Health Dataspace profile registered in CFM with correct EHDS participant type.",
    ],
  },
];
 
// ---------------------------------------------------------------------------
// EHDS roles for registration form
// ---------------------------------------------------------------------------
const EHDS_ROLES = [
  {
    value: "data-holder",
    label: "Data Holder",
    desc: "Provides health data (hospitals, registries)",
  },
  {
    value: "data-user",
    label: "Data User",
    desc: "Consumes health data (researchers, pharma)",
  },
  {
    value: "health-data-access-body",
    label: "Health Data Access Body",
    desc: "Governs data access (regulators)",
  },
];
 
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function deriveStatus(tenant: Tenant): TenantStatus {
  // Nothing provisioned this one and nothing will, so it is not pending either:
  // saying "pending" would promise a DID and a credential that are not coming.
  Iif (tenant.provisioned === false) {
    return "not-provisioned";
  }
  const profiles = tenant.participantProfiles || [];
  if (profiles.length === 0) return "pending";
  if (tenant.provisioningFailed) return "failed";
  // The CFM Tenant Manager says when provisioning is done. The identifier
  // does not: the route sends the DID with the profile, so a profile has one
  // from the first second, and one the agents rolled back keeps it
  // (2026-10-03). The identifier rule below is for the static mock data.
  if (tenant.provisioningComplete) return "active";
  // The tenant and the profile are real, the activities were created, and
  // nothing has completed one since. An animated "Provisioning" clock here
  // promises a DID that is not coming (issue #203, lib/provisioning.ts).
  if (tenant.provisioningStalled) return "stalled";
  // Check both live EDC-V format (identifier) and mock format (did + state)
  if (tenant.vpaSummary && tenant.vpaSummary.total > 0) return "provisioning";
  const hasIdentity = profiles.some(
    (p) =>
      (p.identifier && p.identifier !== "null") ||
      (p.did && p.did !== "null") ||
      p.state === "ACTIVATED",
  );
  if (hasIdentity) return "active";
  return "provisioning";
}
 
function fallbackContact(org: string) {
  const slug = org
    .toLowerCase()
    .replace(/\s+/g, "-")
    .replace(/[^a-z0-9-]/g, "");
  return {
    address: `${org}, Germany`,
    email: `contact@${slug}.de`,
    website: `https://www.${slug}.de`,
    dpoName: "Data Protection Officer",
    dpoEmail: `dpo@${slug}.de`,
  };
}
 
// ---------------------------------------------------------------------------
// Status badge
// ---------------------------------------------------------------------------
function StatusBadge({
  status,
  title,
}: {
  status: TenantStatus;
  title?: string;
}) {
  const t = useT("admin");
  Iif (status === "not-provisioned") {
    return (
      <span
        title={title}
        className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-(--surface-2) text-(--text-secondary) border border-(--border)"
      >
        <Circle size={10} /> {t("Not provisioned")}
      </span>
    );
  }
  if (status === "failed") {
    return (
      <span
        title={title}
        className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-(--role-admin-bg) text-(--role-admin-text) border border-(--role-admin-border)"
      >
        <AlertTriangle size={10} /> {t("Provisioning failed")}
      </span>
    );
  }
  if (status === "stalled") {
    return (
      <span
        title={title}
        className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-(--surface-2) text-(--text-secondary) border border-(--border)"
      >
        <AlertTriangle size={10} /> {t("Provisioning stalled")}
      </span>
    );
  }
  if (status === "active")
    return (
      <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-(--role-user-bg) text-(--role-user-text) border border-(--role-user-border)">
        <CheckCircle2 size={10} /> {t("Active")}
      </span>
    );
  if (status === "provisioning")
    return (
      <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-(--role-hdab-bg) text-(--role-hdab-text) border border-(--role-hdab-border)">
        <Clock size={10} className="animate-pulse" /> {t("Provisioning")}
      </span>
    );
  return (
    <span className="flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-(--surface-2) text-(--text-secondary) border border-(--border)">
      <Circle size={10} /> {t("Pending")}
    </span>
  );
}
 
// ---------------------------------------------------------------------------
// Inline onboarding steps — derived from tenant data (no EDC-V API call needed)
// ---------------------------------------------------------------------------
function OnboardingSteps({ tenant }: { tenant: Tenant }) {
  const t = useT("admin");
  const profiles = tenant.participantProfiles || [];
  const hasProfile = profiles.length > 0;
  const status = deriveStatus(tenant);
  // The hub provisions a participant in one request and undoes it on failure
  // (ADR-078), so a context that is listed has its DID and keys; what can
  // still be outstanding is the credential, which "active" waits for.
  const hasDid =
    status !== "failed" &&
    profiles.some(
      (p) =>
        (p.identifier && p.identifier !== "null") ||
        (p.did && p.did !== "null"),
    );
  // Nothing is in progress on a registration that failed or stalled; a
  // pulsing clock there promises what is not coming.
  const moving = status !== "failed" && status !== "stalled";
 
  const steps = [
    {
      label: t("Registered"),
      done: true,
      inProgress: false,
      desc: t("Organisation registered with the hub"),
    },
    {
      label: t("Participant Context"),
      done: hasProfile && status !== "failed",
      inProgress: !hasProfile && moving,
      desc: t("EDC-V participant context provisioned"),
    },
    {
      label: t("DID Provisioned"),
      done: hasDid,
      inProgress: hasProfile && !hasDid && moving,
      desc: t("Decentralised Identifier (did:web) created via IdentityHub"),
    },
    {
      label: t("Credentials Issued"),
      done: status === "active",
      inProgress: hasDid && status !== "active" && moving,
      desc: t("EHDS Verifiable Credentials available"),
    },
    {
      label: t("Active in Dataspace"),
      done: status === "active",
      inProgress: hasDid && status !== "active" && moving,
      desc: t("Ready to negotiate contracts and transfer data"),
    },
  ];
 
  return (
    <div className="space-y-0">
      {steps.map((s, i) => (
        <div key={s.label} className="flex gap-3">
          <div className="flex flex-col items-center">
            {s.done ? (
              <CheckCircle2
                size={16}
                className="text-(--role-user-text) shrink-0"
              />
            ) : s.inProgress ? (
              <Clock
                size={16}
                className="text-(--role-hdab-text) animate-pulse shrink-0"
              />
            ) : (
              <Circle
                size={16}
                className="text-gray-500 dark:text-gray-400 shrink-0"
              />
            )}
            {i < steps.length - 1 && (
              <div
                className={`w-0.5 h-5 mt-0.5 ${
                  s.done ? "bg-green-700" : "bg-gray-700"
                }`}
              />
            )}
          </div>
          <div className="pb-4">
            <p
              className={`text-xs font-medium ${
                s.done
                  ? "text-(--role-user-text)"
                  : s.inProgress
                    ? "text-(--role-hdab-text)"
                    : "text-(--text-secondary)"
              }`}
            >
              {s.label}
            </p>
            <p className="text-xs text-gray-500 dark:text-gray-400">{s.desc}</p>
          </div>
        </div>
      ))}
      {profiles.length > 0 && (
        <div className="mt-1 space-y-1 border-t border-(--border)/50 pt-3">
          {profiles.map((p, i) => (
            <div
              key={i}
              className="text-xs text-(--text-secondary) font-mono truncate"
            >
              {p.identifier || p.did
                ? `DID: ${p.identifier || p.did}`
                : t("Profile: {id}", {
                    id: p.participantContextId || p.dataspaceProfileId || "",
                  })}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
 
// ---------------------------------------------------------------------------
// Expandable participant card
// ---------------------------------------------------------------------------
/**
 * Removing a participant registered through this page (ADR-085 step 3),
 * EDC_ADMIN only: a first click asks, a second removes. The route refuses a
 * seeded participant with 409, so the button is shown only where it can work.
 */
function RemoveParticipant({
  tenant,
  onRemoved,
}: {
  tenant: Tenant;
  onRemoved: () => void;
}) {
  const t = useT("admin");
  const [confirming, setConfirming] = useState(false);
  const [removing, setRemoving] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  const remove = async () => {
    setRemoving(true);
    setError(null);
    try {
      const res = await fetchApi(
        `/api/participants/${encodeURIComponent(tenant.id)}`,
        { method: "DELETE" },
      );
      const body = (await res.json().catch(() => ({}))) as {
        error?: string;
        detail?: string;
      };
      if (!res.ok) {
        throw new Error(body.detail || body.error || t("Removal failed"));
      }
      onRemoved();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("Removal failed"));
      setRemoving(false);
      setConfirming(false);
    }
  };
 
  return (
    <div className="flex flex-wrap items-center gap-3">
      {confirming ? (
        <>
          <span className="text-xs text-(--text-secondary)">
            {t(
              "Remove this participant from the dataspace? Its context, DID and credentials are deleted.",
            )}
          </span>
          <button
            type="button"
            data-testid="confirm-remove-participant"
            onClick={remove}
            disabled={removing}
            className="inline-flex items-center gap-1.5 rounded-lg border border-red-700 px-3 py-1.5 text-xs font-medium text-red-700 dark:text-red-300 hover:bg-red-900/20 disabled:opacity-60"
          >
            {removing ? (
              <Loader2 size={12} className="animate-spin" />
            ) : (
              <Trash2 size={12} />
            )}
            {removing ? t("Removing…") : t("Remove")}
          </button>
          <button
            type="button"
            onClick={() => setConfirming(false)}
            disabled={removing}
            className="text-xs text-(--text-secondary) hover:underline"
          >
            {t("Cancel")}
          </button>
        </>
      ) : (
        <button
          type="button"
          data-testid="remove-participant"
          onClick={() => setConfirming(true)}
          className="inline-flex items-center gap-1.5 rounded-lg border border-(--border) px-3 py-1.5 text-xs text-(--text-secondary) hover:border-red-700 hover:text-red-700 dark:hover:text-red-300"
        >
          <Trash2 size={12} />
          {t("Remove participant")}
        </button>
      )}
      {error && (
        <p
          role="alert"
          className="w-full text-xs text-red-700 dark:text-red-300"
        >
          {error}
        </p>
      )}
    </div>
  );
}
 
function ParticipantCard({
  tenant,
  defaultExpanded = false,
  onRemoved,
}: {
  tenant: Tenant;
  defaultExpanded?: boolean;
  /** Given when the viewer may remove this participant. */
  onRemoved?: () => void;
}) {
  const t = useT("admin");
  const [expanded, setExpanded] = useState(defaultExpanded);
 
  const name = tenant.properties.displayName || tenant.id;
  const org = tenant.properties.organization || name;
  const role =
    tenant.properties.role ||
    tenant.properties.ehdsParticipantType ||
    "unknown";
  const status = deriveStatus(tenant);
  const contact = CONTACT_DB[name] || fallbackContact(org);
 
  return (
    <div
      className={`rounded-xl border transition-colors ${
        expanded
          ? "border-layer2/60 bg-(--surface)/80"
          : "border-(--border) bg-(--surface)/50 hover:border-gray-600"
      }`}
    >
      {/* Header */}
      <button
        className="w-full text-left flex items-center gap-4 p-4"
        onClick={() => setExpanded(!expanded)}
      >
        <Building2
          size={20}
          className="text-teal-800 dark:text-teal-300 shrink-0"
        />
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap">
            <p className="font-medium text-(--text-primary)">{name}</p>
            <StatusBadge
              status={status}
              title={
                tenant.failedReason ?? tenant.stalledReason ?? tenant.demoReason
              }
            />
          </div>
          <p className="text-xs text-(--text-secondary) mt-0.5">
            {org} · {role} ·{" "}
            {t("{n} profile(s)", {
              n: tenant.participantProfiles?.length || 0,
            })}
          </p>
        </div>
        {expanded ? (
          <ChevronDown size={16} className="text-(--text-secondary) shrink-0" />
        ) : (
          <ChevronRight
            size={16}
            className="text-(--text-secondary) shrink-0"
          />
        )}
      </button>
 
      {/* Expanded body */}
      {expanded && (
        <div className="px-5 pb-5 border-t border-(--border)/50 pt-4 space-y-5">
          {/* Contact columns */}
          <div className="grid sm:grid-cols-2 gap-5">
            <div className="space-y-2">
              <h4 className="text-xs font-semibold text-(--text-secondary) uppercase tracking-wide">
                {t("Organisation")}
              </h4>
              <p className="text-sm font-medium text-(--text-primary)">{org}</p>
              <div className="flex items-start gap-2 text-xs text-(--text-secondary)">
                <MapPin
                  size={12}
                  className="text-(--text-secondary) mt-0.5 shrink-0"
                />
                <span>{contact.address}</span>
              </div>
              <div className="flex items-center gap-2 text-xs">
                <Mail size={12} className="text-(--text-secondary) shrink-0" />
                <a
                  href={`mailto:${contact.email}`}
                  className="text-teal-800 dark:text-teal-300 hover:underline"
                >
                  {contact.email}
                </a>
              </div>
              <div className="flex items-center gap-2 text-xs">
                <ExternalLink
                  size={12}
                  className="text-(--text-secondary) shrink-0"
                />
                <a
                  href={contact.website}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-teal-800 dark:text-teal-300 hover:underline"
                >
                  {contact.website.replace("https://", "")}
                </a>
              </div>
            </div>
 
            <div className="space-y-2">
              <h4 className="text-xs font-semibold text-(--text-secondary) uppercase tracking-wide">
                {t("Data Compliance Officer")}
              </h4>
              <p className="text-sm font-medium text-(--text-primary)">
                {t(contact.dpoName)}
              </p>
              <div className="flex items-center gap-2 text-xs">
                <Mail size={12} className="text-(--text-secondary) shrink-0" />
                <a
                  href={`mailto:${contact.dpoEmail}`}
                  className="text-teal-800 dark:text-teal-300 hover:underline"
                >
                  {contact.dpoEmail}
                </a>
              </div>
              <p className="text-xs text-gray-500 dark:text-gray-400 italic">
                {t("GDPR Art. 37 / EHDS Art. 34 appointed contact")}
              </p>
            </div>
          </div>
 
          {/* Tenant ID */}
          <p className="text-xs text-gray-500 dark:text-gray-400">
            {t("Tenant ID:")}{" "}
            <span className="font-mono text-(--text-secondary)">
              {tenant.id}
            </span>
          </p>
 
          {/* Onboarding progress */}
          <div>
            <h4 className="text-xs font-semibold text-(--text-secondary) uppercase tracking-wide mb-3">
              {t("Onboarding Progress")}
            </h4>
            {(tenant.failedReason ?? tenant.stalledReason) && (
              <p className="mb-3 text-xs text-(--text-secondary)">
                {tenant.failedReason ?? tenant.stalledReason}
              </p>
            )}
            <OnboardingSteps tenant={tenant} />
          </div>
 
          {onRemoved && (
            <RemoveParticipant tenant={tenant} onRemoved={onRemoved} />
          )}
        </div>
      )}
    </div>
  );
}
 
// ---------------------------------------------------------------------------
// EHDS requirements accordion (bottom of page)
// ---------------------------------------------------------------------------
function EhdsRequirements() {
  const t = useT("admin");
  const [open, setOpen] = useState(false);
 
  return (
    <div className="mt-10 border border-(--border) rounded-xl overflow-hidden">
      <button
        className="w-full flex items-center gap-3 px-5 py-4 text-left hover:bg-(--surface-2)/40 transition-colors"
        onClick={() => setOpen(!open)}
      >
        <FileText
          size={18}
          className="text-teal-800 dark:text-teal-300 shrink-0"
        />
        <div className="flex-1">
          <p className="font-semibold text-sm">
            {t("EHDS & Contractual Requirements for Data Sharing")}
          </p>
          <p className="text-xs text-(--text-secondary)">
            {t(
              "Regulatory, NDA, and technical prerequisites before data exchange",
            )}
          </p>
        </div>
        {open ? (
          <ChevronDown size={16} className="text-(--text-secondary)" />
        ) : (
          <ChevronRight size={16} className="text-(--text-secondary)" />
        )}
      </button>
 
      {open && (
        <div className="border-t border-(--border) px-5 py-5 space-y-6">
          {REQUIREMENTS.map((section) => (
            <div key={section.category}>
              <h3 className="text-xs font-semibold text-(--text-secondary) uppercase tracking-wide mb-2">
                {t(section.category)}
              </h3>
              <ul className="space-y-1.5">
                {section.items.map((item, i) => (
                  <li
                    key={i}
                    className="flex items-start gap-2 text-xs text-(--text-primary)"
                  >
                    <span className="text-teal-800 dark:text-teal-300 mt-0.5 shrink-0">
                      •
                    </span>
                    <span>{t(item)}</span>
                  </li>
                ))}
              </ul>
            </div>
          ))}
          <p className="text-xs text-gray-500 dark:text-gray-400 italic pt-2 border-t border-(--border)">
            {t(
              "Note: In this demo environment all participants are pre-seeded. In production, onboarding triggers automated DID provisioning, credential issuance, and policy activation via the CFM orchestration agents.",
            )}
          </p>
        </div>
      )}
    </div>
  );
}
 
// ---------------------------------------------------------------------------
// Main page (inner — uses useSearchParams, must be wrapped in Suspense)
// ---------------------------------------------------------------------------
function OnboardingContent() {
  const t = useT("admin");
  const searchParams = useSearchParams();
  const highlightTenantId = searchParams.get("tenantId");
  const [tenants, setTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [step, setStep] = useState<RegistrationStep>("form");
  const [error, setError] = useState<string | null>(null);
  // Set when the registration was recorded without being provisioned, so the
  // success screen can say so instead of promising a DID (issue #203).
  const [notProvisioned, setNotProvisioned] = useState<string | null>(null);
 
  const [displayName, setDisplayName] = useState("");
  const [organization, setOrganization] = useState("");
  const [role, setRole] = useState("data-holder");
 
  // Only an EDC_ADMIN removes participants, and only one registered here
  // (registeredAt); the static build has nothing to remove.
  const demoPersona = useDemoPersona();
  const { session: tabSession } = useTabSession();
  const roles: string[] = IS_STATIC
    ? demoPersona
      ? [...demoPersona.roles]
      : []
    : tabSession?.roles ?? [];
  const canRemove = (tenant: Tenant) =>
    !IS_STATIC &&
    roles.includes("EDC_ADMIN") &&
    Boolean(tenant.properties.registeredAt);
 
  // quiet: refresh in place, without the loading state, for the polling below.
  const loadTenants = (quiet = false) => {
    if (!quiet) setLoading(true);
    fetchApi("/api/participants/me")
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => {
        setTenants(Array.isArray(d) ? d : d.tenants || []);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  };
 
  useEffect(() => {
    loadTenants();
  }, []);
 
  // Provisioning finishes seconds after the form returns, and the list used to
  // be read only then: a registration that completed showed "Provisioning"
  // until the page was reloaded (2026-10-04). Re-read it while one is still
  // moving. A stalled one stops counting after PROVISIONING_STALL_MS, a failed
  // or active one at once, so this ends by itself.
  const stillProvisioning =
    !IS_STATIC && tenants.some((t) => deriveStatus(t) === "provisioning");
  useEffect(() => {
    if (!stillProvisioning) return;
    const id = setInterval(() => loadTenants(true), POLL_MS);
    return () => clearInterval(id);
  }, [stillProvisioning]);
 
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setStep("submitting");
    setError(null);
    setNotProvisioned(null);
 
    try {
      const res = await fetchApi("/api/participants", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          displayName,
          organization,
          role,
          ehdsParticipantType: role,
        }),
      });
 
      if (!res.ok) {
        const err = await res.json();
        // detail first: "Failed to create participant" on its own told the user
        // nothing and read as though their input were at fault (issue #203).
        throw new Error(err.detail || err.error || t("Registration failed"));
      }
 
      const data = (await res.json()) as Record<string, unknown>;
      if (data.provisioned === false) {
        setNotProvisioned(
          (data.demoReason as string) ||
            t(
              "This deployment cannot provision a participant, so the registration was recorded for the demonstration only.",
            ),
        );
      }
 
      setStep("done");
      loadTenants();
    } catch (err) {
      setError(err instanceof Error ? err.message : t("Registration failed"));
      setStep("form");
    }
  };
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <div className="max-w-4xl mx-auto px-6 py-10">
        <PageIntro
          title={t("Participant Onboarding")}
          icon={UserPlus}
          description={t(
            "Register your organisation as a participant in the European Health Data Space. Each participant receives a DID identity, Verifiable Credentials, and a dataspace profile to enable trusted data sharing.",
          )}
          nextStep={{ href: "/catalog", label: t("Explore Datasets") }}
          infoText={t(
            "After onboarding, your organisation can share or consume health data under EHDS Regulation (EU) 2025/327. The registration creates a participant context, a DID:web identity with its keys, and a membership credential.",
          )}
          docLink={{
            href: "/docs/user-guide",
            label: t("Read the User Guide"),
          }}
        />
 
        {/* Registered participants */}
        {loading ? (
          <div className="flex items-center gap-2 text-(--text-secondary) mb-8">
            <Loader2 size={16} className="animate-spin" />
            {t("Loading registered participants…")}
          </div>
        ) : tenants.length > 0 ? (
          <div className="mb-8">
            <h2 className="text-sm font-semibold text-(--text-secondary) uppercase tracking-wide mb-3">
              {t("Registered Participants")}
            </h2>
            <div className="grid gap-3">
              {tenants.map((t) => (
                <ParticipantCard
                  key={t.id}
                  tenant={t}
                  defaultExpanded={t.id === highlightTenantId}
                  onRemoved={canRemove(t) ? () => loadTenants(true) : undefined}
                />
              ))}
            </div>
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-3">
              {t(
                "Click a participant card to expand contact details and onboarding status.",
              )}
            </p>
          </div>
        ) : null}
 
        {/* Registration form / success */}
        {step === "done" ? (
          <div className="flex flex-col items-center gap-4 py-12 text-center border border-(--border) rounded-xl">
            {notProvisioned ? (
              <Circle size={48} className="text-(--text-secondary)" />
            ) : (
              <CheckCircle2 size={48} className="text-(--role-user-text)" />
            )}
            <h2 className="text-xl font-semibold">
              {notProvisioned
                ? t("Registration Recorded")
                : t("Registration Submitted")}
            </h2>
            <p className="text-(--text-secondary) text-sm max-w-md">
              {notProvisioned ??
                // Not "is active": the context, DID and keys exist when the
                // request returns, the credential only once the issuer has
                // delivered it, which this page cannot promise (#203, ADR-078).
                t(
                  "The participant context, its DID and keys were created, and its MembershipCredential was requested from the issuer. The card shows the participant as active once the issuer has delivered it; if it does not arrive, the card says so.",
                )}
            </p>
            <button
              onClick={() => {
                setStep("form");
                setNotProvisioned(null);
                setDisplayName("");
                setOrganization("");
                setRole("data-holder");
              }}
              className="mt-2 px-4 py-2 border border-gray-600 text-(--text-primary) rounded-lg text-sm hover:border-gray-400"
            >
              {t("Register another participant")}
            </button>
          </div>
        ) : (
          <div className="border border-(--border) rounded-xl p-6">
            <div className="flex items-center gap-2 mb-6">
              <UserPlus
                size={20}
                className="text-teal-800 dark:text-teal-300"
              />
              <h2 className="font-semibold">
                {t("New Participant Registration")}
              </h2>
            </div>
 
            {error && (
              <div className="mb-4 p-3 rounded-sm bg-(--role-admin-bg) border border-(--role-admin-border) text-sm text-(--role-admin-text)">
                {error}
              </div>
            )}
 
            <form onSubmit={handleSubmit} className="space-y-5">
              <div>
                <label className="block text-sm text-(--text-secondary) mb-1">
                  {t("Display Name")}
                </label>
                <input
                  aria-label={t("Display Name")}
                  type="text"
                  required
                  value={displayName}
                  onChange={(e) => setDisplayName(e.target.value)}
                  placeholder={t("e.g. {example}", {
                    example: "University Hospital Berlin",
                  })}
                  className="w-full px-3 py-2 bg-(--surface-2) border border-gray-600 rounded-sm text-sm outline-hidden focus:border-layer2"
                />
              </div>
 
              <div>
                <label className="block text-sm text-(--text-secondary) mb-1">
                  {t("Organisation")}
                </label>
                <input
                  aria-label={t("Organisation")}
                  type="text"
                  required
                  value={organization}
                  onChange={(e) => setOrganization(e.target.value)}
                  placeholder={t("e.g. {example}", {
                    example: "AlphaKlinik Berlin University Hospital",
                  })}
                  className="w-full px-3 py-2 bg-(--surface-2) border border-gray-600 rounded-sm text-sm outline-hidden focus:border-layer2"
                />
              </div>
 
              <div>
                <label className="block text-sm text-(--text-secondary) mb-2">
                  {t("EHDS Role")}
                </label>
                <div className="grid gap-2">
                  {EHDS_ROLES.map((r) => (
                    <label
                      key={r.value}
                      className={`flex items-start gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${
                        role === r.value
                          ? "border-layer2 bg-layer2/10"
                          : "border-(--border) hover:border-gray-500"
                      }`}
                    >
                      <input
                        type="radio"
                        name="role"
                        value={r.value}
                        checked={role === r.value}
                        onChange={() => setRole(r.value)}
                        className="mt-1"
                      />
                      <div>
                        <span className="font-medium text-sm">
                          {t(r.label)}
                        </span>
                        <p className="text-xs text-(--text-secondary) mt-0.5">
                          {t(r.desc)}
                        </p>
                      </div>
                    </label>
                  ))}
                </div>
              </div>
 
              <button
                type="submit"
                disabled={step === "submitting"}
                className="flex items-center gap-2 px-5 py-2.5 bg-(--accent) text-white dark:text-gray-900 rounded-lg text-sm font-medium hover:bg-(--accent-hover) disabled:opacity-50"
              >
                {step === "submitting" ? (
                  <>
                    <Loader2 size={16} className="animate-spin" />
                    {t("Registering…")}
                  </>
                ) : (
                  <>
                    <ShieldCheck size={16} />
                    {t("Register Participant")}
                  </>
                )}
              </button>
            </form>
          </div>
        )}
 
        {/* EHDS + NDA requirements accordion */}
        <EhdsRequirements />
      </div>
    </div>
  );
}
 
// ---------------------------------------------------------------------------
// Default export — wraps content in Suspense (required for useSearchParams)
// ---------------------------------------------------------------------------
export default function OnboardingPage() {
  return (
    <Suspense fallback={null}>
      <OnboardingContent />
    </Suspense>
  );
}