All files / src/app/admin/audit page.tsx

90.54% Statements 67/74
64.08% Branches 116/181
85.71% Functions 24/28
95.31% Lines 61/64

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 9333x                                                                             280x 280x 280x 280x 280x 280x 280x 280x     280x 65x 62x 62x               280x   95x 95x 95x 95x 95x 95x 95x 95x   95x         91x 91x 1x   90x     90x 89x 89x 89x     2x 2x 2x 2x           280x 95x 95x 95x 95x       280x 5x   280x                                                                     1960x     24x 24x                                     1x                                                           476x                                                                                         238x                                                                                         1x                                                                                                       427x                                                                                                                                                                                                                                                                                                                                                             234x 234x 234x         5x 5x 5x 1x   4x   5x                                                                                                                                                                                                                                                                                                                                                                                                                                                     234x                                                                                                                                                                                                                                                                                                                                                                                  
"use client";
 
import { fetchApi } from "@/lib/api";
import { Fragment, useEffect, useState, useCallback } from "react";
import {
  Loader2,
  ArrowRightLeft,
  FileSignature,
  ShieldCheck,
  Download,
  Globe,
  Mail,
  ChevronDown,
  ChevronRight,
  Database,
  AlertTriangle,
} from "lucide-react";
import { AccessLogSection } from "./_components/AccessLogSection";
import { ComplianceButton } from "./_components/ComplianceButton";
import { FilterBar } from "./_components/FilterBar";
import { SpeAuditSection } from "./_components/SpeAuditSection";
import { EMPTY_FILTERS, TABS } from "./_components/constants";
import {
  directionBadge,
  displayName,
  ehdsArticle,
  exportCSV,
  formatBytes,
  statusBadge,
} from "./_components/helpers";
import type {
  AuditData,
  AuditFilters,
  AuditType,
  Participant,
} from "./_components/types";
import { useT } from "@/lib/i18n/translate";
 
export default function AdminAuditPage() {
  const t = useT("admin");
  const [activeTab, setActiveTab] = useState<AuditType>("all");
  const [filters, setFilters] = useState<AuditFilters>(EMPTY_FILTERS);
  const [data, setData] = useState<AuditData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [participants, setParticipants] = useState<Participant[]>([]);
  const [expandedNeg, setExpandedNeg] = useState<Set<string>>(new Set());
 
  // Load participant list once for filter dropdowns
  useEffect(() => {
    fetchApi("/api/admin/audit?type=participants")
      .then((r) => r.json())
      .then((d) => setParticipants(d.participants || []))
      .catch(() => {});
  }, []);
 
  // `isCurrent` turns false once the tab or a filter changed: the answer to
  // an older request is dropped. Without it a slow overview (type=all) that
  // answered after a click on Access Logs replaced that tab's rows with its
  // own, and the tab said "No access logs recorded" (2026-11-08, J911).
  const loadData = useCallback(
    (isCurrent: () => boolean) => {
      setLoading(true);
      const p = new URLSearchParams({ type: activeTab, limit: "50" });
      if (filters.status) p.set("status", filters.status);
      Iif (filters.dateFrom) p.set("dateFrom", filters.dateFrom);
      Iif (filters.dateTo) p.set("dateTo", filters.dateTo);
      if (filters.consumerDid) p.set("consumerDid", filters.consumerDid);
      Iif (filters.providerDid) p.set("providerDid", filters.providerDid);
      if (filters.crossBorder) p.set("crossBorder", filters.crossBorder);
 
      fetchApi(`/api/admin/audit?${p.toString()}`)
        .then(async (r) => {
          // The route answers 502 with { error, detail } when Neo4j is out of
          // reach. Storing that body as data left the page blank on Azure;
          // treat it as the failure it is and show the reason.
          const body = await r.json();
          if (!r.ok || body?.error) {
            throw new Error(body?.detail || body?.error || `HTTP ${r.status}`);
          }
          return body as AuditData;
        })
        .then((d) => {
          if (!isCurrent()) return;
          setData(d);
          setError(null);
          setLoading(false);
        })
        .catch((e: unknown) => {
          Iif (!isCurrent()) return;
          setData(null);
          setError(e instanceof Error ? e.message : String(e));
          setLoading(false);
        });
    },
    [activeTab, filters],
  );
 
  useEffect(() => {
    let current = true;
    loadData(() => current);
    return () => {
      current = false;
    };
  }, [loadData]);
 
  const updateFilter = (patch: Partial<AuditFilters>) =>
    setFilters((f) => ({ ...f, ...patch }));
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <main className="px-8 py-10 max-w-7xl mx-auto space-y-8">
        {/* ── Page header ── */}
        <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
          <div>
            <h1 className="page-header">{t("Audit & Provenance")}</h1>
            {/*
              The subtitle read "Tamper-evident audit trail" and the badge next
              to it read "HIPAA COMPLIANT". Neither was backed by anything in
              the code: the records below are plain Neo4j properties with no
              hash, chain or seal, and HIPAA is a US statute that nothing here
              checks (issue #205). Sealed evidence is issue #204.
            */}
            <p className="text-(--text-secondary) text-lg mt-1">
              {t(
                "Access and provenance records · EHDS Art. 73 · Art. 59 · GDPR Art. 30",
              )}
            </p>
          </div>
          <div
            data-testid="integrity-notice"
            title={t(
              "Transfers, negotiations, credentials and access events are stored as ordinary Neo4j properties. Detached eIDAS seals over contract agreements are issue #204.",
            )}
            className="flex items-center gap-2 px-4 py-2 bg-(--warning)/10 text-(--warning-text) rounded-full border border-(--warning)/20 text-sm font-bold tracking-tight"
          >
            <AlertTriangle size={14} />
            {t("Records are not sealed")}
          </div>
        </div>
 
        {/* Tabs */}
        <div className="flex gap-1 border-b border-(--border)">
          {TABS.map((tab) => (
            <button
              key={tab.key}
              onClick={() => {
                setActiveTab(tab.key);
                setFilters(EMPTY_FILTERS);
              }}
              className={`flex items-center gap-1.5 px-4 py-2.5 text-sm font-bold border-b-2 -mb-px transition-colors ${
                activeTab === tab.key
                  ? "border-(--accent) text-(--accent)"
                  : "border-transparent text-(--text-secondary) hover:text-(--text-primary)"
              }`}
            >
              <tab.icon size={14} />
              {t(tab.label)}
            </button>
          ))}
        </div>
 
        {/* Filter bar (not on overview; secure processing has its own) */}
        {activeTab !== "all" && activeTab !== "spe" && (
          <FilterBar
            filters={filters}
            onChange={updateFilter}
            onClear={() => setFilters(EMPTY_FILTERS)}
            participants={participants}
            tab={activeTab}
          />
        )}
 
        {loading ? (
          <div className="flex items-center gap-2 text-(--text-secondary) mt-6">
            <Loader2 size={16} className="animate-spin" />
            {t("Querying Neo4j…")}
          </div>
        ) : !data ? (
          <div className="mt-6 space-y-1">
            <p className="text-(--text-secondary)">
              {t("Failed to load audit data")}
            </p>
            {error && (
              <p className="text-xs font-mono text-(--text-secondary)">
                {error}
              </p>
            )}
          </div>
        ) : (
          <>
            {/* Overview summary cards */}
            {activeTab === "all" && data.summary?.nodeCounts && (
              <>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                  {Object.entries(data.summary.nodeCounts).map(
                    ([label, count]) => (
                      <div
                        key={label}
                        className="stat-card border-l-(--accent)"
                      >
                        <p className="text-2xl font-black text-(--text-primary) tabular-nums">
                          {count}
                        </p>
                        <p className="text-xs font-medium text-(--text-secondary) mt-1">
                          {label}
                        </p>
                      </div>
                    ),
                  )}
                </div>
 
                {/* Access by consumer */}
                {(data.summary.accessByConsumer?.length ?? 0) > 0 && (
                  <section className="mb-8">
                    <h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
                      <Database
                        size={14}
                        className="text-teal-800 dark:text-teal-300"
                      />
                      {t("Access Activity by Consumer")}
                    </h2>
                    <div className="overflow-auto">
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="text-(--text-secondary) border-b border-(--border)">
                            <th className="text-left py-2 px-2">
                              {t("Consumer")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Total Accesses")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Data Transferred")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Last Access")}
                            </th>
                          </tr>
                        </thead>
                        <tbody>
                          {data.summary.accessByConsumer!.map((row, i) => (
                            <tr
                              key={i}
                              className="border-b border-(--border) hover:bg-(--surface-2)/50"
                            >
                              <td className="py-2 px-2 text-(--text-primary)">
                                {row.consumerName ?? "—"}
                              </td>
                              <td className="py-2 px-2">
                                <span className="inline-block px-1.5 py-0.5 rounded-sm bg-(--role-patient-bg) text-(--role-patient-text) border border-(--role-patient-border) text-[10px] font-semibold">
                                  {row.totalAccesses}×
                                </span>
                              </td>
                              <td className="py-2 px-2 text-(--text-secondary)">
                                {formatBytes(row.totalBytes)}
                              </td>
                              <td className="py-2 px-2 text-(--text-secondary)">
                                {row.lastAccess
                                  ? row.lastAccess.slice(0, 10)
                                  : "—"}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </section>
                )}
              </>
            )}
 
            {/* ── Transfers ──────────────────────────────────────────────── */}
            {(activeTab === "all" || activeTab === "transfers") &&
              data.transfers && (
                <section className="mb-8">
                  <div className="flex items-center justify-between mb-3">
                    <h2 className="font-semibold text-sm flex items-center gap-2">
                      <ArrowRightLeft
                        size={14}
                        className="text-teal-800 dark:text-teal-300"
                      />
                      {t("Data Transfers ({n})", { n: data.transfers.length })}
                    </h2>
                    {data.transfers.length > 0 && (
                      <button
                        onClick={() =>
                          exportCSV(
                            data.transfers as unknown as Record<
                              string,
                              unknown
                            >[],
                            "transfers.csv",
                          )
                        }
                        className="flex items-center gap-1 text-xs text-(--text-secondary) hover:text-(--text-primary) transition-colors"
                      >
                        <Download size={12} /> {t("Export CSV")}
                      </button>
                    )}
                  </div>
                  {data.transfers.length === 0 ? (
                    <p className="text-(--text-secondary) text-sm">
                      {t("No transfers recorded")}
                    </p>
                  ) : (
                    <div className="overflow-auto">
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="text-(--text-secondary) border-b border-(--border)">
                            <th className="text-left py-2 px-2">{t("Dir")}</th>
                            <th className="text-left py-2 px-2">
                              {t("Consumer")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Provider")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Asset")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Purpose")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Status")}
                            </th>
                            <th className="text-left py-2 px-2">{t("Date")}</th>
                            <th className="text-left py-2 px-2">{t("Size")}</th>
                            <th className="text-left py-2 px-2">
                              {t("Accesses")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("EDC Source")}
                            </th>
                            <th className="text-left py-2 px-2">{t("EHDS")}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {data.transfers.map((tr, i) => (
                            <tr
                              key={i}
                              className="border-b border-(--border) hover:bg-(--surface-2)/50"
                            >
                              <td className="py-2 px-2">
                                {directionBadge(tr.direction)}
                              </td>
                              <td className="py-2 px-2">
                                <div className="text-(--text-primary)">
                                  {displayName(
                                    tr.consumerName,
                                    tr.consumerDid,
                                    tr.consumerCountryCode,
                                  )}
                                </div>
                                <div className="mt-0.5">
                                  <ComplianceButton
                                    name={tr.consumerComplianceName}
                                    email={tr.consumerComplianceEmail}
                                  />
                                </div>
                              </td>
                              <td className="py-2 px-2">
                                <div className="text-(--text-primary)">
                                  {displayName(
                                    tr.providerName,
                                    tr.providerDid,
                                    tr.providerCountryCode,
                                  )}
                                </div>
                                <div className="mt-0.5">
                                  <ComplianceButton
                                    name={tr.providerComplianceName}
                                    email={tr.providerComplianceEmail}
                                  />
                                </div>
                              </td>
                              <td className="py-2 px-2 text-(--text-secondary)">
                                {tr.asset || tr.assetId || "—"}
                              </td>
                              <td
                                className="py-2 px-2 text-(--text-secondary) max-w-[140px] truncate"
                                title={tr.purposeOfSharing}
                              >
                                {tr.purposeOfSharing || "—"}
                              </td>
                              <td className="py-2 px-2">
                                {statusBadge(tr.status)}
                                {tr.errorMessage && (
                                  <span
                                    title={String(tr.errorMessage)}
                                    className="ml-1 text-red-400 cursor-help"
                                  >
                                    ⚠
                                  </span>
                                )}
                              </td>
                              <td className="py-2 px-2 text-(--text-secondary)">
                                {(tr.timestamp || tr.transferDate || "—").slice(
                                  0,
                                  10,
                                )}
                              </td>
                              <td className="py-2 px-2 text-(--text-secondary)">
                                {formatBytes(tr.byteSize)}
                              </td>
                              <td className="py-2 px-2">
                                {tr.accessLogCount != null &&
                                tr.accessLogCount > 0 ? (
                                  <span className="inline-block px-1.5 py-0.5 rounded-sm bg-(--role-patient-bg) text-(--role-patient-text) border border-(--role-patient-border) text-[10px] font-semibold">
                                    {tr.accessLogCount}×
                                  </span>
                                ) : (
                                  <span className="text-(--text-secondary)">
                                    —
                                  </span>
                                )}
                              </td>
                              <td className="py-2 px-2">
                                {tr.edcProviderEndpoint ? (
                                  <span
                                    title={tr.edcProviderEndpoint}
                                    className="font-mono text-(--text-secondary) text-[10px] truncate max-w-[100px] block cursor-help"
                                  >
                                    {tr.edcProviderEndpoint.replace(
                                      /^https?:\/\//,
                                      "",
                                    )}
                                  </span>
                                ) : (
                                  "—"
                                )}
                              </td>
                              <td className="py-2 px-2">
                                {tr.crossBorder ? (
                                  <span className="flex items-center gap-0.5 text-orange-800 dark:text-orange-400">
                                    <Globe size={10} />
                                    {ehdsArticle(tr.policyId)}
                                  </span>
                                ) : (
                                  ehdsArticle(tr.policyId)
                                )}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </section>
              )}
 
            {/* ── Negotiations ───────────────────────────────────────────── */}
            {(activeTab === "all" || activeTab === "negotiations") &&
              data.negotiations && (
                <section className="mb-8">
                  <div className="flex items-center justify-between mb-3">
                    <h2 className="font-semibold text-sm flex items-center gap-2">
                      <FileSignature
                        size={14}
                        className="text-teal-800 dark:text-teal-300"
                      />
                      {t("Contract Negotiations ({n})", {
                        n: data.negotiations.length,
                      })}
                    </h2>
                    {data.negotiations.length > 0 && (
                      <button
                        onClick={() =>
                          exportCSV(
                            data.negotiations as unknown as Record<
                              string,
                              unknown
                            >[],
                            "negotiations.csv",
                          )
                        }
                        className="flex items-center gap-1 text-xs text-(--text-secondary) hover:text-(--text-primary) transition-colors"
                      >
                        <Download size={12} /> {t("Export CSV")}
                      </button>
                    )}
                  </div>
                  {data.negotiations.length === 0 ? (
                    <p className="text-(--text-secondary) text-sm">
                      {t("No negotiations recorded")}
                    </p>
                  ) : (
                    <div className="overflow-auto">
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="text-(--text-secondary) border-b border-(--border)">
                            <th className="text-left py-2 px-2 w-5"></th>
                            <th className="text-left py-2 px-2">
                              {t("Consumer")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Provider")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Asset")}
                            </th>
                            <th className="text-left py-2 px-2">
                              {t("Status")}
                            </th>
                            <th className="text-left py-2 px-2">{t("Date")}</th>
                            <th className="text-left py-2 px-2">
                              {t("Accesses")}
                            </th>
                            <th className="text-left py-2 px-2">{t("EHDS")}</th>
                          </tr>
                        </thead>
                        <tbody>
                          {data.negotiations.map((n, nIdx) => {
                            const rowKey =
                              n.id || n.contractId || `neg-${nIdx}`;
                            const isOpen = expandedNeg.has(rowKey);
                            return (
                              <Fragment key={rowKey}>
                                <tr
                                  className="border-b border-(--border) hover:bg-(--surface-2)/40 cursor-pointer"
                                  onClick={() =>
                                    setExpandedNeg((prev) => {
                                      const next = new Set(prev);
                                      if (isOpen) {
                                        next.delete(rowKey);
                                      } else {
                                        next.add(rowKey);
                                      }
                                      return next;
                                    })
                                  }
                                >
                                  <td className="py-2 px-2 text-(--text-secondary)">
                                    {isOpen ? (
                                      <ChevronDown size={11} />
                                    ) : (
                                      <ChevronRight size={11} />
                                    )}
                                  </td>
                                  <td className="py-2 px-2">
                                    <div className="text-(--text-primary)">
                                      {displayName(
                                        n.consumerName,
                                        n.consumerDid,
                                        n.consumerCountryCode,
                                      )}
                                    </div>
                                    <div className="mt-0.5">
                                      <ComplianceButton
                                        name={n.consumerComplianceName}
                                        email={n.consumerComplianceEmail}
                                      />
                                    </div>
                                  </td>
                                  <td className="py-2 px-2">
                                    <div className="text-(--text-primary)">
                                      {displayName(
                                        n.providerName,
                                        n.providerDid,
                                        n.providerCountryCode,
                                      )}
                                    </div>
                                    <div className="mt-0.5">
                                      <ComplianceButton
                                        name={n.providerComplianceName}
                                        email={n.providerComplianceEmail}
                                      />
                                    </div>
                                  </td>
                                  <td className="py-2 px-2 text-(--text-secondary)">
                                    {n.asset || n.assetId || "—"}
                                  </td>
                                  <td className="py-2 px-2">
                                    {statusBadge(n.status)}
                                  </td>
                                  <td className="py-2 px-2 text-(--text-secondary)">
                                    {(
                                      n.timestamp ||
                                      n.negotiationDate ||
                                      "—"
                                    ).slice(0, 10)}
                                  </td>
                                  <td className="py-2 px-2">
                                    {n.accessLogCount != null &&
                                    n.accessLogCount > 0 ? (
                                      <span className="inline-block px-1.5 py-0.5 rounded-sm bg-(--role-patient-bg) text-(--role-patient-text) border border-(--role-patient-border) text-[10px] font-semibold">
                                        {n.accessLogCount}×
                                      </span>
                                    ) : (
                                      <span className="text-(--text-secondary)">
                                        —
                                      </span>
                                    )}
                                  </td>
                                  <td className="py-2 px-2">
                                    {n.crossBorder ? (
                                      <span className="flex items-center gap-0.5 text-orange-800 dark:text-orange-400">
                                        <Globe size={10} />
                                        {ehdsArticle(n.policyId)}
                                      </span>
                                    ) : (
                                      ehdsArticle(n.policyId)
                                    )}
                                  </td>
                                </tr>
 
                                {/* Expanded policy card */}
                                {isOpen && (
                                  <tr className="border-b border-(--border) bg-(--surface)/60">
                                    <td colSpan={8} className="px-6 py-4">
                                      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        {/* Policy details */}
                                        <div className="border border-(--border) rounded-lg p-3">
                                          <p className="text-[10px] font-semibold text-(--text-secondary) uppercase mb-2">
                                            {t("Policy Details")}
                                          </p>
                                          <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                                            <span className="text-(--text-secondary)">
                                              {t("Purpose")}
                                            </span>
                                            <span className="text-(--text-primary)">
                                              {n.policyPurpose ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Legal Basis")}
                                            </span>
                                            <span className="text-(--text-primary)">
                                              {n.policyLegalBasis ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Permitted")}
                                            </span>
                                            <span className="text-(--text-primary)">
                                              {n.policyPermittedUses ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Prohibited")}
                                            </span>
                                            <span className="text-red-800 dark:text-red-400">
                                              {n.policyProhibitedUses ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Data Minimisation")}
                                            </span>
                                            <span className="text-(--text-primary)">
                                              {n.policyDataMinimisation ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Retention")}
                                            </span>
                                            <span className="text-(--text-primary)">
                                              {n.policyRetentionDays
                                                ? t("{n} days", {
                                                    n: n.policyRetentionDays,
                                                  })
                                                : "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Total Accesses")}
                                            </span>
                                            <span className="text-teal-300 font-semibold">
                                              {n.accessCount ?? 0}×
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Last Access")}
                                            </span>
                                            <span className="text-(--text-primary)">
                                              {n.lastAccessAt
                                                ? n.lastAccessAt.slice(0, 10)
                                                : "—"}
                                            </span>
                                          </div>
                                        </div>
 
                                        {/* EDC endpoints + contract ID */}
                                        <div className="border border-(--border) rounded-lg p-3">
                                          <p className="text-[10px] font-semibold text-(--text-secondary) uppercase mb-2">
                                            {t("EDC Endpoints & Contract")}
                                          </p>
                                          <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                                            <span className="text-(--text-secondary)">
                                              {t("Consumer EDC")}
                                            </span>
                                            <span className="font-mono text-(--text-secondary) break-all">
                                              {n.consumerEdcEndpoint ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Provider EDC")}
                                            </span>
                                            <span className="font-mono text-(--text-secondary) break-all">
                                              {n.providerEdcEndpoint ?? "—"}
                                            </span>
                                            <span className="text-(--text-secondary)">
                                              {t("Contract ID")}
                                            </span>
                                            <span className="font-mono text-(--text-secondary)">
                                              {n.contractId ?? "—"}
                                            </span>
                                          </div>
                                        </div>
                                      </div>
                                    </td>
                                  </tr>
                                )}
                              </Fragment>
                            );
                          })}
                        </tbody>
                      </table>
                    </div>
                  )}
                </section>
              )}
 
            {/* ── Credentials ────────────────────────────────────────────── */}
            {(activeTab === "all" || activeTab === "credentials") &&
              data.credentials && (
                <section className="mb-8">
                  <h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
                    <ShieldCheck
                      size={14}
                      className="text-teal-800 dark:text-teal-300"
                    />
                    {t("Verifiable Credentials ({n})", {
                      n: data.credentials.length,
                    })}
                  </h2>
                  {data.credentials.length === 0 ? (
                    <p className="text-(--text-secondary) text-sm">
                      {t("No credentials recorded")}
                    </p>
                  ) : (
                    <div className="overflow-auto">
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="text-(--text-secondary) border-b border-(--border)">
                            <th className="text-left py-2 px-2">
                              {t("Participant")}
                            </th>
                            <th className="text-left py-2 px-2">{t("Type")}</th>
                            <th className="text-left py-2 px-2">
                              {t("Issued")}
                            </th>
                          </tr>
                        </thead>
                        <tbody>
                          {data.credentials.map((c, i) => (
                            <tr
                              key={i}
                              className="border-b border-(--border) hover:bg-(--surface-2)/50"
                            >
                              <td className="py-2 px-2 text-(--text-primary)">
                                {c.participant ||
                                  c.subjectDid
                                    ?.replace("did:web:", "")
                                    .replace(/%3A/g, ":") ||
                                  "—"}
                              </td>
                              <td className="py-2 px-2 text-(--text-primary)">
                                {c.credentialType || c.type || "—"}
                              </td>
                              <td className="py-2 px-2 text-(--text-secondary)">
                                {(c.issuedAt || c.issuanceDate || "—").slice(
                                  0,
                                  10,
                                )}
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  )}
                </section>
              )}
            {/* ── Secure processing (ADR-068, #774) ──────────────────────── */}
            {activeTab === "spe" && (
              <SpeAuditSection events={data.speEvents ?? []} />
            )}
            {/* ── Access Logs ────────────────────────────────────────────── */}
            {activeTab === "supervision" && (
              <section className="mb-8" data-testid="supervision-section">
                <h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
                  <AlertTriangle
                    size={14}
                    className="text-amber-700 dark:text-amber-300"
                  />
                  {t("Findings of non-compliance, Art. 63 ({n})", {
                    n: data.findings?.length ?? 0,
                  })}
                </h2>
                {!data.findings || data.findings.length === 0 ? (
                  <p className="text-(--text-secondary) text-sm mb-6">
                    {t("No finding recorded")}
                  </p>
                ) : (
                  <div className="overflow-auto mb-6">
                    <table className="w-full text-xs">
                      <thead>
                        <tr className="text-(--text-secondary) border-b border-(--border)">
                          <th className="text-left py-2 px-2">{t("Party")}</th>
                          <th className="text-left py-2 px-2">
                            {t("Finding")}
                          </th>
                          <th className="text-left py-2 px-2">{t("Status")}</th>
                          <th className="text-left py-2 px-2">
                            {t("Notified")}
                          </th>
                          <th className="text-left py-2 px-2">
                            {t("Views by")}
                          </th>
                          <th className="text-left py-2 px-2">
                            {t("Measure")}
                          </th>
                          <th className="text-left py-2 px-2">{t("GDPR")}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.findings.map((f) => (
                          <tr
                            key={f.findingId}
                            className="border-b border-(--border) align-top"
                            data-testid="finding-row"
                          >
                            <td className="py-2 px-2">
                              <div>{f.partyName ?? f.partyId}</div>
                              {f.permitId && (
                                <div className="font-mono text-(--text-secondary)">
                                  {f.permitId}
                                </div>
                              )}
                            </td>
                            <td className="py-2 px-2">
                              <div>{f.description}</div>
                              <div className="font-mono text-(--text-secondary)">
                                {f.findingId}
                              </div>
                              {f.views && (
                                <div className="text-(--text-secondary)">
                                  {t("Views: {views}", { views: f.views })}
                                </div>
                              )}
                            </td>
                            <td className="py-2 px-2">{f.status}</td>
                            <td className="py-2 px-2 whitespace-nowrap">
                              {f.notifiedAt?.slice(0, 10)}
                            </td>
                            <td className="py-2 px-2 whitespace-nowrap">
                              {f.respondBy?.slice(0, 10)}
                            </td>
                            <td className="py-2 px-2">
                              {f.measure ?? "—"}
                              {f.revokedPermit ? ` (${f.revokedPermit})` : ""}
                              {f.measureNote ? `: ${f.measureNote}` : ""}
                            </td>
                            <td className="py-2 px-2">
                              {f.gdprBreach ? t("authority informed") : "—"}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
                <h2 className="font-semibold text-sm mb-3 flex items-center gap-2">
                  <Mail
                    size={14}
                    className="text-teal-800 dark:text-teal-300"
                  />
                  {t("Requests for information, Art. 63(1) ({n})", {
                    n: data.informationRequests?.length ?? 0,
                  })}
                </h2>
                {!data.informationRequests ||
                data.informationRequests.length === 0 ? (
                  <p className="text-(--text-secondary) text-sm">
                    {t("No request recorded")}
                  </p>
                ) : (
                  <div className="overflow-auto">
                    <table className="w-full text-xs">
                      <thead>
                        <tr className="text-(--text-secondary) border-b border-(--border)">
                          <th className="text-left py-2 px-2">{t("Party")}</th>
                          <th className="text-left py-2 px-2">
                            {t("Question")}
                          </th>
                          <th className="text-left py-2 px-2">{t("Status")}</th>
                          <th className="text-left py-2 px-2">{t("Asked")}</th>
                          <th className="text-left py-2 px-2">
                            {t("Answer by")}
                          </th>
                          <th className="text-left py-2 px-2">{t("Answer")}</th>
                        </tr>
                      </thead>
                      <tbody>
                        {data.informationRequests.map((r) => (
                          <tr
                            key={r.requestId}
                            className="border-b border-(--border) align-top"
                            data-testid="information-request-row"
                          >
                            <td className="py-2 px-2">
                              {r.partyName ?? r.partyId}
                            </td>
                            <td className="py-2 px-2">{r.question}</td>
                            <td className="py-2 px-2">{r.status}</td>
                            <td className="py-2 px-2 whitespace-nowrap">
                              {r.requestedAt?.slice(0, 10)}
                            </td>
                            <td className="py-2 px-2 whitespace-nowrap">
                              {r.answerBy?.slice(0, 10)}
                            </td>
                            <td className="py-2 px-2">{r.answer ?? "—"}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                )}
              </section>
            )}
 
            {activeTab === "accesslogs" && (
              <AccessLogSection logs={data.accesslogs ?? []} />
            )}
          </>
        )}
      </main>
    </div>
  );
}