All files / src/app/compliance page.tsx

97.56% Statements 80/82
70.61% Branches 137/194
96.15% Functions 25/26
97.46% Lines 77/79

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 10073x                                                                   229x 229x 229x 229x 229x 229x 229x 229x 229x 229x 229x 229x       229x 229x 229x     229x     229x 2x 2x 2x 2x 2x 2x 4x                 229x 61x   55x   55x 55x 55x     55x 55x             54x 1x 1x   53x     54x 53x 54x     55x       229x 14x 14x 3x 3x   11x 11x 11x         10x 10x       10x       229x                                                                                                                                                                                                                                                                                                                                 55x                   55x 55x 85x 85x 85x         85x     55x 30x 30x 30x 15x           15x     85x   85x 85x       14x                                                                                                                                                                                                                                                                                       1x 1x                                                                                   9x                                                                                                                                                                         167x                                                                                                                                                                                                                                                                                                                                                                                                                   56x                                                                                                                                                                                                                                                                 79x                                                                                                                       1140x                              
"use client";
 
import { fetchApi } from "@/lib/api";
import { useDemoPersona } from "@/lib/use-demo-persona";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import {
  ShieldCheck,
  AlertCircle,
  BadgeCheck,
  Key,
  Globe,
  Lock,
} from "lucide-react";
import Link from "next/link";
import { IS_STATIC } from "@/lib/static-export";
import { ApplicationPanel } from "./_components/ApplicationPanel";
import { DecisionClock } from "./_components/DecisionClock";
import { TrustedIssuers } from "./_components/TrustedIssuers";
import { COMPLIANCE_LABELS } from "./_components/constants";
import { complianceLevel, isUndecided, rowKey } from "./_components/helpers";
import type {
  ComplianceLevel,
  Consumer,
  Credential,
  DatasetOption,
  MatrixRow,
  Result,
  SpeSession,
  TrustCenter,
} from "./_components/types";
import { T, useT } from "@/lib/i18n/translate";
 
export default function CompliancePage() {
  const t = useT("compliance");
  const [_consumers, setConsumers] = useState<Consumer[]>([]);
  const [_datasets, setDatasets] = useState<DatasetOption[]>([]);
  const [matrix, setMatrix] = useState<MatrixRow[]>([]);
  const [credentials, setCredentials] = useState<Credential[]>([]);
  const [trustCenters, setTrustCenters] = useState<TrustCenter[]>([]);
  const [speSessions, setSpeSessions] = useState<SpeSession[]>([]);
  const [trustCenterRefused, setTrustCenterRefused] = useState(false);
  const [optionsLoading, setOptionsLoading] = useState(true);
  const [detailRow, setDetailRow] = useState<MatrixRow | null>(null);
  const [detailResult, setDetailResult] = useState<Result | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
 
  // Only the access body decides (Art. 57(1)(a)); everyone else with access
  // to this page reads. Static demo: the persona carries the roles.
  const { data: session } = useSession();
  const demoPersona = useDemoPersona();
  const roles: readonly string[] = IS_STATIC
    ? demoPersona?.roles ?? []
    : (session as { roles?: string[] } | null)?.roles ?? [];
  const canDecide = roles.includes("HDAB_AUTHORITY");
 
  // After a decision the matrix and the open row are re-read from the graph.
  const reloadMatrix = async () => {
    try {
      const d = await fetchApi("/api/compliance").then((r) => r.json());
      const rows: MatrixRow[] = d.matrix ?? [];
      setMatrix(rows);
      setDetailRow((current) =>
        current
          ? rows.find((r) => rowKey(r) === rowKey(current)) ?? current
          : current,
      );
    } catch {
      // keep what is on screen
    }
  };
 
  // Load matrix, credentials, and trust centers on mount
  useEffect(() => {
    Promise.all([
      fetchApi("/api/compliance")
        .then((r) => r.json())
        .then((d) => {
          setConsumers(d.consumers ?? []);
          setDatasets(d.datasets ?? []);
          setMatrix(d.matrix ?? []);
        }),
      fetchApi("/api/credentials")
        .then((r) => r.json())
        .then((d) => setCredentials(d.credentials ?? []))
        .catch(() => {}),
      fetchApi("/api/trust-center")
        .then((r) => {
          // The register admits trust centre operators and the administrator;
          // an access body gets 403 until #571 decides otherwise. Say so
          // rather than show an empty section.
          if (r.status === 403) {
            setTrustCenterRefused(true);
            return null;
          }
          return r.json();
        })
        .then((d) => {
          if (!d) return;
          setTrustCenters(d.trustCenters ?? []);
          setSpeSessions(d.speSessions ?? []);
        })
        .catch(() => {}),
    ]).finally(() => setOptionsLoading(false));
  }, []);
 
  // Drill down into a specific participant row
  const showDetail = async (row: MatrixRow) => {
    setDetailRow(row);
    if (!row.datasetId) {
      setDetailResult({ compliant: false, chain: [] });
      return;
    }
    setDetailLoading(true);
    try {
      const r = await fetchApi(
        `/api/compliance?consumerId=${encodeURIComponent(
          row.consumerId,
        )}&datasetId=${encodeURIComponent(row.datasetId)}`,
      );
      const data = await r.json();
      setDetailResult(data);
    } catch {
      setDetailResult({ compliant: false, chain: [] });
    } finally {
      setDetailLoading(false);
    }
  };
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <div className="max-w-5xl mx-auto px-6 py-10">
        {/* ── Page header ── */}
        <div className="mb-8">
          <h1 className="page-header">{t("EHDS Compliance Overview")}</h1>
          <p className="text-(--text-secondary) text-lg mt-1">
            {t("HDAB approval chain · Regulation (EU) 2025/327, Art. 67 to 73")}
          </p>
          <div className="flex gap-4 mt-4 text-sm">
            <Link
              href="/eehrxf"
              className="font-bold text-(--accent) hover:underline"
            >
              {t("← EEHRxF Profiles")}
            </Link>
            <Link
              href="/compliance/tck"
              className="font-bold text-(--accent) hover:underline"
            >
              {t("Protocol TCK →")}
            </Link>
            <Link
              href="/permits"
              className="font-bold text-(--accent) hover:underline"
            >
              {t("Public register →")}
            </Link>
          </div>
        </div>
 
        {/* ── Intro description ── */}
        <div className="rounded-lg border border-(--border) bg-(--surface) p-4 mb-8 text-sm text-(--text-secondary) space-y-2">
          <p>
            <T
              area="compliance"
              tags={{ b: <strong className="text-(--text-primary)" /> }}
            >
              {
                "The <b>EHDS Compliance Matrix</b> shows the approval chain status for every dataspace participant. Under Regulation (EU) 2025/327, secondary use of health data requires a complete chain:"
              }
            </T>
          </p>
          <ol className="list-decimal list-inside space-y-1 ml-2">
            <li>
              <T
                area="compliance"
                tags={{ b: <strong className="text-(--text-primary)" /> }}
              >
                {
                  "<b>Access Application</b> · the data user applies with purpose, justification and ethics assessment (Art. 67)"
                }
              </T>
            </li>
            <li>
              <T
                area="compliance"
                tags={{ b: <strong className="text-(--text-primary)" /> }}
              >
                {
                  "<b>HDAB decision</b> · the health data access body assesses the Art. 68(1) criteria and issues or refuses a data permit within three months (Art. 68)"
                }
              </T>
            </li>
            <li>
              <T
                area="compliance"
                tags={{ b: <strong className="text-(--text-primary)" /> }}
              >
                {
                  "<b>Dataset Grant</b> · the permit names the dataset it grants access to (Art. 68(3))"
                }
              </T>
            </li>
            <li>
              <T
                area="compliance"
                tags={{ b: <strong className="text-(--text-primary)" /> }}
              >
                {
                  "<b>Contract</b> · the data user accesses the data only under that permit, in a secure processing environment (Art. 61(1), Art. 73)"
                }
              </T>
            </li>
          </ol>
          <p>
            <T area="compliance" tags={{ b: <strong /> }}>
              {
                "<b>Decision due:</b> the date by which the access body must issue or refuse the data permit: three months after it received the application (Art. 68(4)). <b>Late</b> means the body has done neither by that date. The applicant may not access any data until it decides (Art. 61(1)), and the application and the decision must be published (Art. 57(1)(j)). The delay is the access body's compliance issue, not the applicant's."
              }
            </T>
          </p>
          <p>
            {t(
              "Click a row for the application and the chain. Signed in as the access body, the row also carries the decision: a refused or missing permit blocks the transfer in step 5.",
            )}
          </p>
        </div>
 
        {/* ── Compliance Matrix ── */}
        <div className="mb-8">
          <h2
            id="compliance-matrix-heading"
            className="text-sm font-semibold mb-3 text-(--text-primary)"
          >
            {t("Participant Compliance Matrix")}
          </h2>
          {optionsLoading ? (
            <div className="text-(--text-secondary) text-sm">
              {t("Loading compliance data from graph…")}
            </div>
          ) : matrix.length === 0 ? (
            <div className="text-(--text-secondary) text-sm">
              {t("No participants found in the knowledge graph.")}
            </div>
          ) : (
            // Focusable and named, so a keyboard can scroll the wide matrix
            // sideways (WCAG 2.1.1; axe scrollable-region-focusable).
            <div
              role="region"
              aria-labelledby="compliance-matrix-heading"
              tabIndex={0}
              className="overflow-x-auto rounded-lg border border-(--border)"
            >
              <table className="text-xs w-full border-collapse">
                <thead>
                  <tr className="bg-(--surface) text-(--text-secondary)">
                    <th className="text-left px-3 py-2 font-medium">
                      {t("Participant")}
                    </th>
                    <th className="text-left px-3 py-2 font-medium">
                      {t("Role")}
                    </th>
                    <th className="text-center px-3 py-2 font-medium">
                      {t("Application")}
                    </th>
                    <th className="text-center px-3 py-2 font-medium">
                      {t("HDAB Approval")}
                    </th>
                    <th className="text-left px-3 py-2 font-medium">
                      {t("Decision due")}
                    </th>
                    <th className="text-left px-3 py-2 font-medium">
                      {t("Dataset")}
                    </th>
                    <th className="text-center px-3 py-2 font-medium">
                      {t("Contract")}
                    </th>
                    <th className="text-center px-3 py-2 font-medium">
                      {t("EHDS Art.")}
                    </th>
                    <th className="text-center px-3 py-2 font-medium">
                      {t("Status")}
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {/* One row per application, one per participant without any.
                      The access body's inbox: undecided applications first,
                      the nearest Art. 68(4) deadline on top. */}
                  {(() => {
                    const LEVEL_RANK: Record<ComplianceLevel, number> = {
                      full: 6,
                      approved: 5,
                      review: 4,
                      pending: 3,
                      governance: 2,
                      none: 1,
                      rejected: 0,
                      revoked: 0,
                    };
                    const seen = new Map<string, MatrixRow>();
                    for (const row of matrix) {
                      const key = rowKey(row);
                      const existing = seen.get(key);
                      Eif (
                        !existing ||
                        LEVEL_RANK[complianceLevel(row)] >
                          LEVEL_RANK[complianceLevel(existing)]
                      ) {
                        seen.set(key, row);
                      }
                    }
                    return [...seen.values()].sort((a, b) => {
                      const ua = isUndecided(a);
                      const ub = isUndecided(b);
                      if (ua !== ub) return ua ? -1 : 1;
                      Iif (ua && ub) {
                        return (
                          (a.daysToDecision ?? Infinity) -
                          (b.daysToDecision ?? Infinity)
                        );
                      }
                      return a.consumerName.localeCompare(b.consumerName);
                    });
                  })().map((row) => {
                    const level = complianceLevel(row);
                    const isSelected =
                      detailRow !== null && rowKey(detailRow) === rowKey(row);
                    return (
                      <tr
                        key={rowKey(row)}
                        data-application-id={row.applicationId ?? undefined}
                        onClick={() => showDetail(row)}
                        className={`border-t border-(--border) cursor-pointer transition-colors ${
                          isSelected
                            ? "bg-(--accent-surface)"
                            : "hover:bg-(--surface)"
                        }`}
                      >
                        <td className="px-3 py-2 font-medium text-(--text-primary)">
                          {row.consumerName}
                        </td>
                        <td className="px-3 py-2">
                          <span className="text-(--text-secondary)">
                            {row.consumerType}
                          </span>
                        </td>
                        <td className="px-3 py-2 text-center">
                          {row.hasApplication ? (
                            <span
                              className={
                                row.applicationStatus === "APPROVED"
                                  ? "text-(--success-text)"
                                  : row.applicationStatus === "REJECTED"
                                    ? "text-(--danger-text)"
                                    : "text-(--warning-text)"
                              }
                              title={row.applicationStatus ?? ""}
                            >
                              {row.applicationStatus === "APPROVED"
                                ? `✓ ${t("Approved")}`
                                : row.applicationStatus === "REJECTED"
                                  ? `✗ ${t("Rejected")}`
                                  : row.applicationStatus === "UNDER_REVIEW"
                                    ? `◔ ${t("Under Review")}`
                                    : row.applicationStatus === "PENDING"
                                      ? `◔ ${t("Pending")}`
                                      : row.applicationStatus === "INCOMPLETE"
                                        ? `◔ ${t("Incomplete")}`
                                        : row.applicationStatus ?? "✓"}
                            </span>
                          ) : (
                            <span className="text-(--text-secondary)">—</span>
                          )}
                        </td>
                        <td className="px-3 py-2 text-center">
                          {row.hasApproval ? (
                            <span
                              className={
                                row.approvalStatus === "APPROVED"
                                  ? "text-(--success-text)"
                                  : row.approvalStatus === "REJECTED" ||
                                      row.approvalStatus === "REVOKED"
                                    ? "text-(--danger-text)"
                                    : "text-(--warning-text)"
                              }
                              title={row.approvalStatus ?? ""}
                            >
                              {row.approvalStatus === "APPROVED"
                                ? `✓ ${t("Approved")}`
                                : row.approvalStatus === "REJECTED"
                                  ? `✗ ${t("Denied")}`
                                  : row.approvalStatus === "REVOKED"
                                    ? `✗ ${t("Revoked")}`
                                    : row.approvalStatus ?? "—"}
                            </span>
                          ) : (
                            <span className="text-(--text-secondary)">—</span>
                          )}
                        </td>
                        <td className="px-3 py-2 whitespace-nowrap">
                          <DecisionClock row={row} />
                        </td>
                        <td className="px-3 py-2 text-(--text-primary)">
                          {row.datasetTitle ? (
                            <span title={row.datasetId ?? ""}>
                              {row.datasetTitle}
                            </span>
                          ) : (
                            <span className="text-(--text-secondary)">—</span>
                          )}
                        </td>
                        <td className="px-3 py-2 text-center">
                          {row.hasContract ? (
                            <span className="text-(--success-text)">✓</span>
                          ) : (
                            <span className="text-(--text-secondary)">—</span>
                          )}
                        </td>
                        <td className="px-3 py-2 text-center text-(--text-secondary)">
                          {row.ehdsArticle ?? "—"}
                        </td>
                        <td className="px-3 py-2 text-center">
                          <span
                            className={`inline-flex items-center gap-1 text-xs font-medium px-2 py-0.5 rounded border ${
                              level === "full"
                                ? "bg-(--badge-active-bg) text-(--badge-active-text) border-(--badge-active-border)"
                                : level === "approved"
                                  ? "bg-(--role-holder-bg) text-(--role-holder-text) border-(--role-holder-border)"
                                  : level === "pending"
                                    ? "bg-(--role-hdab-bg) text-(--role-hdab-text) border-(--role-hdab-border)"
                                    : level === "review"
                                      ? "bg-(--role-hdab-bg) text-(--role-hdab-text) border-(--role-hdab-border)"
                                      : level === "rejected" ||
                                          level === "revoked"
                                        ? "bg-(--badge-inactive-bg) text-(--badge-inactive-text) border-(--badge-inactive-border)"
                                        : level === "governance"
                                          ? "bg-(--role-trust-bg) text-(--role-trust-text) border-(--role-trust-border)"
                                          : "bg-(--surface-2) text-(--text-secondary) border-(--border)"
                            }`}
                          >
                            {level === "full" && <ShieldCheck size={12} />}
                            {(level === "pending" || level === "review") && (
                              <AlertCircle size={12} />
                            )}
                            {(level === "rejected" || level === "revoked") && (
                              <AlertCircle size={12} />
                            )}
                            {level === "governance" && (
                              <ShieldCheck size={12} />
                            )}
                            {level === "approved" && <ShieldCheck size={12} />}
                            {COMPLIANCE_LABELS[level]}
                          </span>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
 
          {/* Detail panel — shows when a row is clicked */}
          {detailRow && (
            <div className="mt-4 rounded-xl border border-(--border) bg-(--surface) p-4">
              <div className="flex items-center justify-between mb-3">
                <h3 className="font-semibold text-sm text-(--text-primary)">
                  {detailRow.consumerName} — {t("Approval Chain Detail")}
                </h3>
                <button
                  onClick={() => {
                    setDetailRow(null);
                    setDetailResult(null);
                  }}
                  className="text-xs text-(--text-secondary) hover:text-(--text-primary)"
                >
                  {t("Close")}
                </button>
              </div>
 
              <ApplicationPanel
                key={rowKey(detailRow)}
                row={detailRow}
                canDecide={canDecide}
                onDecided={reloadMatrix}
              />
 
              {detailLoading ? (
                <div className="text-(--text-secondary) text-xs">
                  {t("Checking approval chain…")}
                </div>
              ) : !detailResult ? null : detailResult.compliant ? (
                <div>
                  <div className="flex items-center gap-2 mb-3 text-sm">
                    <ShieldCheck size={16} className="text-(--success-text)" />
                    <span className="text-(--success-text) font-medium">
                      {t("Full HDAB approval chain found")}
                    </span>
                  </div>
                  {detailResult.chain.length > 0 && (
                    <table className="text-xs w-full border-collapse">
                      <thead>
                        <tr className="text-(--text-secondary) border-b border-(--border)">
                          <th className="text-left pb-1">{t("Application")}</th>
                          <th className="text-left pb-1">{t("Status")}</th>
                          <th className="text-left pb-1">{t("Approval")}</th>
                          <th className="text-left pb-1">
                            {t("EHDS Article")}
                          </th>
                          <th className="text-left pb-1">{t("Contract")}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {detailResult.chain.map((c, i) => (
                          <tr key={i} className="border-b border-(--border)">
                            <td className="py-1 pr-2 font-mono">
                              {c.applicationId}
                            </td>
                            <td className="py-1 pr-2 text-(--success-text)">
                              {c.applicationStatus}
                            </td>
                            <td className="py-1 pr-2 font-mono">
                              {c.approvalId}
                            </td>
                            <td className="py-1 pr-2">{c.ehdsArticle}</td>
                            <td className="py-1 font-mono text-(--text-secondary)">
                              {c.contract ?? "—"}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}
                </div>
              ) : (
                <div>
                  <div className="flex items-center gap-2 mb-2 text-sm">
                    <AlertCircle size={16} className="text-(--warning-text)" />
                    <span className="text-(--warning-text) font-medium">
                      {t("Incomplete approval chain")}
                    </span>
                  </div>
                  <div className="text-xs text-(--text-secondary) space-y-1">
                    <p>
                      <strong>{t("Application:")}</strong>{" "}
                      {detailRow.hasApplication
                        ? `✓ ${detailRow.applicationStatus ?? t("submitted")}`
                        : `✗ ${t("No AccessApplication submitted")}`}
                    </p>
                    <p>
                      <strong>{t("HDAB Approval:")}</strong>{" "}
                      {detailRow.hasApproval
                        ? `✓ ${detailRow.approvalStatus ?? t("exists")}`
                        : `✗ ${t("No HDABApproval linked")}`}
                    </p>
                    <p>
                      <strong>{t("Dataset grant:")}</strong>{" "}
                      {detailRow.datasetId
                        ? `✓ ${detailRow.datasetTitle}`
                        : `✗ ${t(
                            "No GRANTS_ACCESS_TO relationship to a dataset",
                          )}`}
                    </p>
                    <p>
                      <strong>{t("Contract:")}</strong>{" "}
                      {detailRow.hasContract
                        ? `✓ ${t("Contract governs DataProduct")}`
                        : `✗ ${t("No Contract → DataProduct → Dataset chain")}`}
                    </p>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
 
        {/* ── Verifiable Credentials Trust Section ── */}
        <div className="mt-12 border-t border-(--border) pt-8">
          <div className="flex items-center gap-2 mb-1">
            <Key size={18} className="text-blue-800 dark:text-blue-300" />
            <h2 className="text-xl font-bold">
              {t("EHDS Verifiable Credentials")}
            </h2>
          </div>
          <p className="text-(--text-secondary) text-sm mb-6">
            {t(
              "DCP credential definitions registered on IssuerService, presented during DSP negotiation",
            )}
          </p>
 
          {credentials.length === 0 ? (
            <div className="text-(--text-secondary) text-sm">
              {optionsLoading
                ? t("Loading…")
                : t("No credentials found in graph.")}
            </div>
          ) : (
            <div className="space-y-4">
              {credentials.map((vc) => (
                <div
                  key={vc.credentialId}
                  className="rounded-lg border border-(--border) bg-(--surface-2)/50 p-4"
                >
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <BadgeCheck
                        size={16}
                        className={
                          vc.status === "active"
                            ? "text-(--badge-active-text)"
                            : "text-(--badge-inactive-text)"
                        }
                      />
                      <span className="font-semibold text-sm">
                        {vc.credentialType}
                      </span>
                      {vc.participantRole && (
                        // On the card surface with a layer-5 border: a tint of
                        // the layer colour behind its own text was 3.92:1 in
                        // the dark theme (WCAG 1.4.3).
                        <span className="text-xs px-2 py-0.5 rounded-sm border border-(--layer5)/40 bg-(--surface) text-(--layer5-text)">
                          {vc.participantRole}
                        </span>
                      )}
                    </div>
                    <span
                      className={`text-xs font-medium px-2 py-0.5 rounded border ${
                        vc.status === "active"
                          ? "bg-(--badge-active-bg) text-(--badge-active-text) border-(--badge-active-border)"
                          : "bg-(--badge-inactive-bg) text-(--badge-inactive-text) border-(--badge-inactive-border)"
                      }`}
                    >
                      {vc.status}
                    </span>
                  </div>
 
                  <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-(--text-secondary)">
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Holder:")}
                      </span>{" "}
                      {vc.holderName ?? "—"}
                      {vc.holderType && (
                        <span className="text-(--text-secondary)">
                          {" "}
                          [{vc.holderType}]
                        </span>
                      )}
                    </div>
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Subject:")}
                      </span>{" "}
                      <span className="font-mono">
                        {vc.subjectDid?.replace(
                          /did:web:identityhub%3A7083:/,
                          "",
                        )}
                      </span>
                    </div>
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Issuer:")}
                      </span>{" "}
                      <span className="font-mono">
                        {vc.issuerDid?.replace(
                          /did:web:issuerservice%3A10016:/,
                          "",
                        )}
                      </span>
                    </div>
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Format:")}
                      </span>{" "}
                      VC1_0_JWT
                    </div>
 
                    {/* Type-specific details */}
                    {vc.purpose && (
                      <div className="col-span-2">
                        <span className="text-(--text-secondary)">
                          {t("Purpose:")}
                        </span>{" "}
                        {vc.purpose}
                      </div>
                    )}
                    {vc.datasetId && (
                      <div className="col-span-2">
                        <span className="text-(--text-secondary)">
                          {t("Dataset:")}
                        </span>{" "}
                        <span className="font-mono">{vc.datasetId}</span>
                      </div>
                    )}
                    {vc.completeness != null && (
                      <div className="col-span-2 mt-1">
                        <span className="text-(--text-secondary)">
                          {t("Quality:")}
                        </span>{" "}
                        {t("Completeness")}{" "}
                        <span className="text-(--success-text)">
                          {(vc.completeness * 100).toFixed(0)}%
                        </span>
                        {" · "}
                        {t("Conformance")}{" "}
                        <span className="text-(--success-text)">
                          {((vc.conformance ?? 0) * 100).toFixed(0)}%
                        </span>
                        {" · "}
                        {t("Timeliness")}{" "}
                        <span className="text-(--success-text)">
                          {((vc.timeliness ?? 0) * 100).toFixed(0)}%
                        </span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
 
          {/* Trust chain diagram */}
          <div className="mt-6 rounded-lg border border-(--border) bg-(--surface)/50 p-4">
            <h3 className="text-sm font-semibold mb-3 text-(--text-primary)">
              {t("DCP Trust Chain")} — {t("Credential Presentation Flow")}
            </h3>
            <div className="flex items-center gap-2 text-xs text-(--text-secondary) flex-wrap">
              <span className="px-2 py-1 rounded-sm bg-layer1/20 text-blue-800 dark:text-blue-300 font-medium">
                IssuerService
              </span>
              <span>→ {t("signs VC")} →</span>
              <span className="px-2 py-1 rounded-sm bg-layer2/20 text-teal-800 dark:text-teal-300 font-medium">
                IdentityHub
              </span>
              <span>→ {t("stores")} →</span>
              <span className="px-2 py-1 rounded-sm bg-layer3/20 text-green-800 dark:text-green-300 font-medium">
                DCP Presentation
              </span>
              <span>→ {t("verifies")} →</span>
              <span className="px-2 py-1 rounded-sm bg-layer5/20 text-purple-800 dark:text-purple-300 font-medium">
                Policy Engine
              </span>
              <span>→ {t("evaluates")} →</span>
              <span className="px-2 py-1 rounded-sm bg-(--badge-active-bg) text-(--badge-active-text) border border-(--badge-active-border) font-medium">
                ✓ {t("Access Granted")}
              </span>
            </div>
          </div>
          <TrustedIssuers />
        </div>
 
        {/* ── Phase 18: Trust Center Section ── */}
        <div
          id="trust-center"
          className="mt-12 border-t border-(--border) pt-8"
        >
          <div className="flex items-center gap-2 mb-1">
            <Lock size={18} className="text-blue-800 dark:text-blue-300" />
            <h2 className="text-xl font-bold">
              {t("Trust Center: Pseudonym Resolution")}
            </h2>
          </div>
          <p className="text-(--text-secondary) text-sm mb-6">
            {t(
              "EHDS Art. 66 and 73: HDAB-designated trust centers enabling cross-provider longitudinal patient linkage without exposing real identities to researchers. Provider pseudonyms are resolved to research pseudonyms inside the Secure Processing Environment only.",
            )}
          </p>
 
          {optionsLoading ? (
            <div className="text-(--text-secondary) text-sm">
              {t("Loading trust centers…")}
            </div>
          ) : trustCenterRefused ? (
            <div
              role="status"
              data-testid="trust-center-refused"
              className="text-(--text-secondary) text-sm"
            >
              {t(
                "Your role cannot read the trust centre register. It is open to trust centre operators and the dataspace administrator; whether a health data access body may read it is still to be decided.",
              )}
            </div>
          ) : trustCenters.length === 0 ? (
            <div className="text-(--text-secondary) text-sm">
              <T
                area="compliance"
                tags={{
                  code: (
                    <code className="font-mono text-xs bg-(--surface-2) px-1 py-0.5 rounded-sm" />
                  ),
                }}
              >
                {
                  "No trust centers found. Run <code>neo4j/seed-trust-center.cypher</code> to seed demo data."
                }
              </T>
            </div>
          ) : (
            <div className="space-y-4">
              {trustCenters.map((tc) => (
                <div
                  key={tc.name}
                  data-testid="trust-center-card"
                  className="rounded-lg border border-(--border) bg-(--surface-2)/50 p-4"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <Globe
                        size={16}
                        className="text-blue-800 dark:text-blue-300"
                      />
                      <span className="font-semibold text-sm">{tc.name}</span>
                      <span className="text-xs px-2 py-0.5 rounded-sm bg-(--surface-2) text-(--text-primary)">
                        {tc.country}
                      </span>
                    </div>
                    <span
                      className={`text-xs font-medium px-2 py-0.5 rounded border ${
                        tc.status === "active"
                          ? "bg-(--badge-active-bg) text-(--badge-active-text) border-(--badge-active-border)"
                          : "bg-(--badge-inactive-bg) text-(--badge-inactive-text) border-(--badge-inactive-border)"
                      }`}
                    >
                      {tc.status}
                    </span>
                  </div>
 
                  <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-(--text-secondary) mb-3">
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Operated by:")}
                      </span>{" "}
                      {tc.operatedBy}
                    </div>
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Protocol:")}
                      </span>{" "}
                      {tc.protocol}
                    </div>
                    <div className="col-span-2">
                      <span className="text-(--text-secondary)">DID:</span>{" "}
                      <span className="font-mono">{tc.did}</span>
                    </div>
                    {tc.hdabApprovalId && (
                      <div>
                        <span className="text-(--text-secondary)">
                          {t("HDAB Approval:")}
                        </span>{" "}
                        <span className="font-mono">{tc.hdabApprovalId}</span>{" "}
                        <span
                          className={
                            tc.hdabApprovalStatus === "approved"
                              ? "text-(--success-text)"
                              : "text-(--warning-text)"
                          }
                        >
                          [{tc.hdabApprovalStatus}]
                        </span>
                      </div>
                    )}
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Datasets covered:")}
                      </span>{" "}
                      {tc.datasetCount}
                    </div>
                    <div>
                      <span className="text-(--text-secondary)">
                        {t("Active RPSNs:")}
                      </span>{" "}
                      <span className="text-(--success-text)">
                        {tc.activeRpsnCount}
                      </span>
                    </div>
                    {tc.recognisedCountries.length > 0 && (
                      <div className="col-span-2">
                        <span className="text-(--text-secondary)">
                          {t(
                            "Mutual recognition (HealthData@EU, EHDS Art. 75):",
                          )}
                        </span>{" "}
                        {tc.recognisedCountries.join(", ")}
                      </div>
                    )}
                  </div>
 
                  {/* Cross-border pseudonym resolution flow */}
                  <div className="rounded-sm bg-(--surface)/60 p-3 text-xs text-(--text-secondary) flex items-center gap-2 flex-wrap">
                    <span className="px-2 py-1 rounded-sm bg-layer1/20 text-blue-800 dark:text-blue-300 font-medium">
                      Provider PSN
                    </span>
                    <span>→ {t("HDAB-auth resolve")} →</span>
                    <span className="px-2 py-1 rounded-sm bg-layer5/20 text-purple-800 dark:text-purple-300 font-medium">
                      {tc.name}
                    </span>
                    <span>→ RPSN →</span>
                    <span className="px-2 py-1 rounded-sm bg-layer3/20 text-green-800 dark:text-green-300 font-medium">
                      SPE (TEE)
                    </span>
                    <span>→ {t("aggregate-only")} →</span>
                    <span className="px-2 py-1 rounded-sm bg-(--badge-active-bg) text-(--badge-active-text) border border-(--badge-active-border) font-medium">
                      {t("Researcher")}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
 
          {/* SPE Sessions */}
          {speSessions.length > 0 && (
            <div className="mt-6">
              <h3 className="text-sm font-semibold mb-3 text-(--text-primary)">
                {t("Active SPE Sessions (TEE-Attested)")}
              </h3>
              <table className="text-xs w-full border-collapse">
                <thead>
                  <tr className="text-(--text-secondary) border-b border-(--border)">
                    <th className="text-left pb-1">{t("Session ID")}</th>
                    <th className="text-left pb-1">{t("Study")}</th>
                    <th className="text-left pb-1">{t("Status")}</th>
                    <th className="text-left pb-1">k-anon</th>
                    <th className="text-left pb-1">{t("Output Policy")}</th>
                    <th className="text-left pb-1">{t("Created by")}</th>
                  </tr>
                </thead>
                <tbody>
                  {speSessions.map((s) => (
                    <tr
                      key={s.sessionId}
                      className="border-b border-(--border)"
                      data-testid="spe-session-row"
                    >
                      <td className="py-1 pr-2 font-mono text-(--text-primary)">
                        {s.sessionId}
                      </td>
                      <td className="py-1 pr-2">{s.studyId}</td>
                      <td className="py-1 pr-2">
                        <span
                          className={
                            s.status === "active"
                              ? "text-(--success-text)"
                              : "text-(--text-secondary)"
                          }
                        >
                          {s.status}
                        </span>
                      </td>
                      <td className="py-1 pr-2">≥ {s.kAnonymityThreshold}</td>
                      <td className="py-1 pr-2">{s.outputPolicy}</td>
                      <td className="py-1 font-mono text-(--text-secondary)">
                        {s.createdBy?.split(":").pop()}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
 
          {/* Security model summary */}
          <div className="mt-6 rounded-lg border border-(--border) bg-(--surface)/50 p-4">
            <h3 className="text-sm font-semibold mb-3 text-(--text-primary)">
              {t("Security Model: Threat Mitigations")}
            </h3>
            <div className="space-y-1 text-xs text-(--text-secondary)">
              {[
                [
                  "Researcher accesses raw data",
                  "SPE + TEE enforce aggregate-only output (k ≥ 5)",
                ],
                [
                  "Provider re-identification",
                  "Provider-specific pseudonyms (local key per provider)",
                ],
                [
                  "Cross-provider linkage leak",
                  "Trust Center under HDAB authority only",
                ],
                [
                  "Trust Center collusion",
                  "Stateless or key-split design; full audit trail",
                ],
                [
                  "Pseudonym reversal",
                  "One-way HMAC mapping; revocable by HDAB",
                ],
              ].map(([threat, mitigation]) => (
                <div key={threat} className="flex gap-2">
                  <span className="text-(--warning-text) shrink-0">⚠</span>
                  <span className="text-(--text-secondary) shrink-0 w-56">
                    {threat}
                  </span>
                  <span className="text-(--success-text)">{mitigation}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}