All files / src/app/settings page.tsx

87.5% Statements 119/136
71.5% Branches 138/193
90.24% Functions 37/41
90.24% Lines 111/123

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                                                2x           2x                                                                                                                   181x 181x   181x         181x       181x   181x       181x 37x 37x     181x 181x 181x 181x 181x 181x 181x 181x     181x 73x                                     181x                         181x 37x 33x   33x 33x 33x   2x       181x 73x 29x 29x 29x           30x 30x                             2x 1x 1x 1x 1x   1x 1x       33x 33x 33x 30x 33x 33x   2x   2x 2x     28x   3x   33x         31x 31x 30x       30x 30x 31x 6x 6x     25x 24x     21x     21x 21x       31x 4x   31x 4x                     4x                       20x     1x         5x 5x 5x 5x 5x         4x   3x 3x 3x         3x 3x   2x   5x         181x                                             181x 37x                       144x                                                                                       1x       151x                                                                                                                                                                                                                                                     700x                   12x                                 63x   63x       63x 53x 63x   63x 63x                                                                                                                                   53x                                                     3x                                   6x                                       6x 6x 8x     6x   6x                                                                                                                                                                                                                                                                                
"use client";
 
import { fetchApi } from "@/lib/api";
import { DEMO_PERSONAS } from "@/lib/auth";
import { useDemoPersona } from "@/lib/use-demo-persona";
import { useTabSession } from "@/lib/use-tab-session";
import { useEffect, useMemo, useState, type ElementType } from "react";
import {
  Loader2,
  Settings2,
  Save,
  CheckCircle2,
  AlertCircle,
  User,
  Globe,
  Phone,
  Mail,
  MapPin,
  ShieldCheck,
  ShieldOff,
  RefreshCw,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
 
const IS_STATIC = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
 
/**
 * Maps a demo persona username to the tenant IDs they should see.
 * Admin and HDAB see all tenants; others see only their own organisation.
 */
const PERSONA_TENANT_MAP: Record<string, string[]> = {
  edcadmin: [], // empty = show all (admin)
  regulator: ["medreg-de-id", "irs-fr-id"],
  clinicuser: ["alpha-klinik-id"],
  researcher: ["pharmaco-research-id"],
  lmcuser: ["limburg-mc-id"],
  patient1: ["alpha-klinik-id"],
  patient2: ["limburg-mc-id"],
};
 
interface VPA {
  id: string;
  type: string;
  state: string;
}
 
interface ParticipantProfile {
  id: string;
  identifier: string;
  tenantId: string;
  error?: boolean;
  vpas?: VPA[];
  properties?: {
    "cfm.vpa.state"?: {
      participantContextId?: string;
      credentialRequest?: string;
      holderPid?: string;
    };
    displayName?: string;
  };
}
 
interface Tenant {
  id: string;
  version: number;
  properties: Record<string, string>;
  participantProfiles: ParticipantProfile[];
}
 
interface VerifiableCredential {
  id?: string;
  type?: string[];
  issuer?: string;
  issuanceDate?: string;
  expirationDate?: string;
  credentialSubject?: Record<string, unknown>;
}
 
interface CredentialContext {
  profileId: string;
  participantContextId: string | null;
  did?: string;
  credentials: VerifiableCredential[];
  error?: string;
}
 
export default function SettingsPage() {
  /* ── Current user context ── */
  const demoPersona = useDemoPersona();
  const { session: tabSession } = useTabSession();
 
  const currentRoles: string[] = IS_STATIC
    ? demoPersona
      ? [...demoPersona.roles]
      : []
    : tabSession?.roles ?? [];
  const currentUsername: string = IS_STATIC
    ? demoPersona?.username ?? ""
    : tabSession?.username ?? "";
 
  const isPatient = currentRoles.includes("PATIENT");
  const isAdmin =
    currentRoles.includes("EDC_ADMIN") ||
    currentRoles.includes("HDAB_AUTHORITY");
 
  // Resolve which organisation this user belongs to
  const currentOrg = useMemo(() => {
    const persona = DEMO_PERSONAS.find((p) => p.username === currentUsername);
    return persona?.organisation ?? "";
  }, [currentUsername]);
 
  const [allTenants, setAllTenants] = useState<Tenant[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Tenant | null>(null);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [saveError, setSaveError] = useState("");
  const [credentials, setCredentials] = useState<CredentialContext[]>([]);
  const [credsLoading, setCredsLoading] = useState(false);
 
  // Filter tenants by persona — admin sees all, others see their own
  const tenants = useMemo(() => {
    Eif (isAdmin) return allTenants;
    const allowed = PERSONA_TENANT_MAP[currentUsername];
    if (allowed && allowed.length > 0) {
      return allTenants.filter((t) => allowed.includes(t.id));
    }
    // Fallback: match by organisation name in displayName
    if (currentOrg) {
      const orgBase = currentOrg.replace(/ \(patient\)$/, "");
      const matched = allTenants.filter(
        (t) =>
          t.properties.displayName === orgBase ||
          t.properties.organization?.includes(orgBase),
      );
      if (matched.length > 0) return matched;
    }
    return allTenants;
  }, [allTenants, isAdmin, currentUsername, currentOrg]);
 
  // Editable contact field state — seeded from tenant properties
  const [form, setForm] = useState({
    displayName: "",
    organization: "",
    contactPerson: "",
    email: "",
    phone: "",
    address: "",
    city: "",
    postalCode: "",
    country: "",
    website: "",
  });
 
  useEffect(() => {
    fetchApi("/api/participants/me")
      .then((r) => (r.ok ? r.json() : []))
      .then((d) => {
        const list = Array.isArray(d) ? d : d.tenants || [];
        setAllTenants(list);
        setLoading(false);
      })
      .catch(() => setLoading(false));
  }, []);
 
  // When tenants (filtered) change, auto-select the first one
  useEffect(() => {
    if (tenants.length > 0 && !tenants.find((t) => t.id === selected?.id)) {
      setSelected(tenants[0]);
      seedForm(tenants[0]);
      loadCredentials(tenants[0].id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tenants]);
 
  function seedForm(t: Tenant) {
    const p = t.properties || {};
    setForm({
      displayName: p.displayName || "",
      organization: p.organization || "",
      contactPerson: p.contactPerson || "",
      email: p.email || "",
      phone: p.phone || "",
      address: p.address || "",
      city: p.city || "",
      postalCode: p.postalCode || "",
      country: p.country || "",
      website: p.website || "",
    });
  }
 
  function handleSelect(id: string) {
    const t = tenants.find((t) => t.id === id) || null;
    setSelected(t);
    Eif (t) {
      seedForm(t);
      loadCredentials(t.id);
    }
    setSaved(false);
    setSaveError("");
  }
 
  async function loadCredentials(tenantId: string) {
    setCredsLoading(true);
    try {
      const res = await fetchApi(`/api/participants/${tenantId}/credentials`);
      const data = res.ok ? await res.json() : [];
      const arr = Array.isArray(data) ? data : [];
      if (
        arr.length > 0 &&
        arr.some((c: CredentialContext) => c.credentials?.length > 0)
      ) {
        setCredentials(arr);
        return;
      }
      // Fallback: load from global credentials endpoint and match by tenant DID
      await loadCredentialsFallback(tenantId);
    } catch {
      await loadCredentialsFallback(tenantId).catch(() => setCredentials([]));
    } finally {
      setCredsLoading(false);
    }
  }
 
  async function loadCredentialsFallback(tenantId: string) {
    try {
      const res = await fetchApi("/api/credentials");
      Iif (!res.ok) {
        setCredentials([]);
        return;
      }
      const raw = await res.json();
      const allCreds = raw.credentials || raw || [];
      if (!Array.isArray(allCreds)) {
        setCredentials([]);
        return;
      }
      // Resolve DIDs for this tenant
      const tenant = tenants.find((t) => t.id === tenantId);
      const dids = new Set(
        (tenant?.participantProfiles || [])
          .map((pp) => {
            const id = pp.identifier
              ? decodeURIComponent(pp.identifier)
              : undefined;
            const d = (pp as unknown as { did?: string }).did;
            return id || d;
          })
          .filter(Boolean),
      );
      const matched = allCreds.filter(
        (c: { subjectDid?: string }) => c.subjectDid && dids.has(c.subjectDid),
      );
      if (matched.length > 0) {
        setCredentials([
          {
            profileId: "mock-fallback",
            participantContextId: null,
            credentials: matched.map(
              (c: {
                credentialId?: string;
                credentialType?: string;
                issuerDid?: string;
                issuedAt?: string;
                expiresAt?: string;
              }) => ({
                id: c.credentialId,
                type: c.credentialType ? [c.credentialType] : [],
                issuer: c.issuerDid,
                issuanceDate: c.issuedAt,
                expirationDate: c.expiresAt,
                credentialSubject: c as unknown as Record<string, unknown>,
              }),
            ),
          },
        ]);
      } else {
        setCredentials([]);
      }
    } catch {
      setCredentials([]);
    }
  }
 
  async function handleSave() {
    Iif (!selected) return;
    setSaving(true);
    setSaveError("");
    try {
      const res = await fetchApi(`/api/participants/${selected.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ properties: form }),
      });
      if (!res.ok) throw new Error(await res.text());
      // Update local state
      setAllTenants((prev) =>
        prev.map((t) =>
          t.id === selected.id
            ? { ...t, properties: { ...t.properties, ...form } }
            : t,
        ),
      );
      setSaved(true);
      setTimeout(() => setSaved(false), 3000);
    } catch (e: unknown) {
      setSaveError(e instanceof Error ? e.message : "Save failed");
    } finally {
      setSaving(false);
    }
  }
 
  // Patients do not have DCP business credentials — redirect away
  Iif (isPatient && !isAdmin) {
    return (
      <div className="min-h-screen bg-[var(--bg)]">
        <div className="max-w-3xl mx-auto px-6 py-10 text-center">
          <Settings2
            size={40}
            className="text-[var(--text-secondary)] mx-auto mb-4"
          />
          <p className="text-[var(--text-secondary)] mb-2">
            Patient accounts use personal health credentials (eIDAS 2.0 /
            OIDC4VP), not DCP business profiles.
          </p>
          <a
            href="/patient"
            className="text-sm text-teal-800 dark:text-teal-300 hover:underline"
          >
            Go to My Health →
          </a>
        </div>
      </div>
    );
  }
 
  if (loading) {
    return (
      <div className="min-h-screen bg-[var(--bg)]">
        <div className="max-w-3xl mx-auto px-6 py-10">
          <div className="flex items-center gap-2 text-[var(--text-secondary)]">
            <Loader2 size={16} className="animate-spin" />
            Loading settings…
          </div>
        </div>
      </div>
    );
  }
 
  return (
    <div className="min-h-screen bg-[var(--bg)]">
      <div className="max-w-3xl mx-auto px-6 py-10">
        <PageIntro
          title={isAdmin ? "Dataspace Settings" : "Participant Settings"}
          icon={Settings2}
          description={
            isAdmin
              ? "Manage all participant profiles across the dataspace. Update display names, contact details, and notification settings."
              : `Manage your profile and preferences for ${
                  currentOrg || "your organisation"
                }. Update display name, contact details, and notification settings.`
          }
          prevStep={{ href: "/admin/audit", label: "Audit & Provenance" }}
          infoText="Changes are saved to the tenant-manager API and reflected across all dataspace interactions. Your DID:web identity and credentials remain unchanged."
          docLink={{ href: "/docs/user-guide", label: "User Guide" }}
        />
 
        {tenants.length === 0 ? (
          <div className="text-center py-12">
            <Settings2
              size={40}
              className="text-[var(--text-secondary)] mx-auto mb-4"
            />
            <p className="text-[var(--text-secondary)] mb-2">
              No participant profile found
            </p>
            <a
              href="/onboarding"
              className="text-sm text-teal-800 dark:text-teal-300 hover:underline"
            >
              Register first →
            </a>
          </div>
        ) : (
          <>
            {/* Tenant selector */}
            <div className="mb-6">
              <label className="block text-sm text-[var(--text-secondary)] mb-1">
                Active Profile
              </label>
              <select
                aria-label="Active Profile"
                value={selected?.id || ""}
                onChange={(e) => handleSelect(e.target.value)}
                className="w-full px-3 py-2 bg-[var(--surface-2)] border border-[var(--border-ui)] rounded text-sm"
              >
                {tenants.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.properties.displayName || t.id}
                  </option>
                ))}
              </select>
            </div>
 
            {selected && (
              <div className="border border-[var(--border)] rounded-xl divide-y divide-gray-700">
                {/* Identity (read-only) */}
                <div className="p-6">
                  <h2 className="font-semibold mb-4 flex items-center gap-2">
                    <User
                      size={16}
                      className="text-teal-800 dark:text-teal-300"
                    />
                    Identity
                  </h2>
                  <div className="grid gap-4 sm:grid-cols-2">
                    <div>
                      <label className="text-xs text-[var(--text-secondary)]">
                        EHDS Role
                      </label>
                      <p className="text-sm font-medium text-[var(--text-primary)] mt-0.5">
                        {selected.properties.ehdsParticipantType ||
                          selected.properties.role ||
                          "—"}
                      </p>
                    </div>
                    <div>
                      <label className="text-xs text-[var(--text-secondary)]">
                        Tenant ID
                      </label>
                      <p className="font-mono text-xs text-[var(--text-secondary)] break-all mt-0.5">
                        {selected.id}
                      </p>
                    </div>
                  </div>
                </div>
 
                {/* Editable contact & organisation fields */}
                <div className="p-6">
                  <h2 className="font-semibold mb-4 flex items-center gap-2">
                    <Settings2
                      size={16}
                      className="text-teal-800 dark:text-teal-300"
                    />
                    Profile &amp; Contact Details
                  </h2>
                  <div className="grid gap-4 sm:grid-cols-2">
                    {(
                      [
                        {
                          key: "displayName",
                          label: "Display Name",
                          icon: User,
                          placeholder: "e.g. AlphaKlinik Berlin",
                        },
                        {
                          key: "organization",
                          label: "Organisation",
                          icon: Settings2,
                          placeholder: "Legal entity name",
                        },
                        {
                          key: "contactPerson",
                          label: "Contact Person",
                          icon: User,
                          placeholder: "Full name",
                        },
                        {
                          key: "email",
                          label: "Email",
                          icon: Mail,
                          placeholder: "contact@example.de",
                          type: "email",
                        },
                        {
                          key: "phone",
                          label: "Phone",
                          icon: Phone,
                          placeholder: "+49 30 …",
                          type: "tel",
                        },
                        {
                          key: "website",
                          label: "Website",
                          icon: Globe,
                          placeholder: "https://",
                          type: "url",
                        },
                        {
                          key: "address",
                          label: "Street Address",
                          icon: MapPin,
                          placeholder: "Street & number",
                        },
                        {
                          key: "city",
                          label: "City",
                          icon: MapPin,
                          placeholder: "Berlin",
                        },
                        {
                          key: "postalCode",
                          label: "Postal Code",
                          icon: MapPin,
                          placeholder: "10117",
                        },
                        {
                          key: "country",
                          label: "Country",
                          icon: Globe,
                          placeholder: "DE",
                        },
                      ] as {
                        key: keyof typeof form;
                        label: string;
                        icon: ElementType;
                        placeholder: string;
                        type?: string;
                      }[]
                    ).map(({ key, label, icon: Icon, placeholder, type }) => (
                      <div key={key}>
                        <label className="text-xs text-[var(--text-secondary)] flex items-center gap-1 mb-1">
                          <Icon size={11} />
                          {label}
                        </label>
                        <input
                          aria-label={label}
                          type={type || "text"}
                          value={form[key]}
                          onChange={(e) =>
                            setForm((f) => ({ ...f, [key]: e.target.value }))
                          }
                          placeholder={placeholder}
                          className="w-full px-3 py-1.5 bg-[var(--surface-2)] border border-[var(--border-ui)] rounded text-sm text-[var(--text-primary)] placeholder-[var(--text-secondary)] focus:outline-none focus:border-layer2"
                        />
                      </div>
                    ))}
                  </div>
                </div>
 
                {/* Dataspace Profiles */}
                <div className="p-6">
                  <h2 className="font-semibold mb-3">Dataspace Profiles</h2>
                  {selected.participantProfiles?.length > 0 ? (
                    <div className="space-y-3">
                      {selected.participantProfiles.map((pp, i) => {
                        const ctxId =
                          pp.properties?.["cfm.vpa.state"]
                            ?.participantContextId || "—";
                        const did = pp.identifier
                          ? decodeURIComponent(pp.identifier)
                          : "—";
                        const allDisposed =
                          pp.vpas?.length &&
                          pp.vpas.every((v) => v.state === "disposed");
                        const hasError = pp.error && !allDisposed;
                        const activeVpas =
                          pp.vpas?.filter((v) => v.state === "active") || [];
                        return (
                          <div
                            key={pp.id || i}
                            className={`p-3 rounded-lg border text-xs space-y-1.5 ${
                              hasError
                                ? "bg-red-100 dark:bg-red-950/30 border-red-300 dark:border-red-800/50"
                                : allDisposed
                                  ? "bg-yellow-100 dark:bg-yellow-950/20 border-yellow-300 dark:border-yellow-800/40"
                                  : "bg-[var(--surface-2)]/50 border-[var(--border)]"
                            }`}
                          >
                            {hasError && (
                              <div className="flex items-center gap-1.5 text-red-800 dark:text-red-400 mb-1">
                                <AlertCircle size={12} />
                                <span>Provisioning failed</span>
                              </div>
                            )}
                            {allDisposed && (
                              <div className="flex items-center gap-1.5 text-yellow-800 dark:text-yellow-400 mb-1">
                                <AlertCircle size={12} />
                                <span>
                                  VPAs disposed — re-run{" "}
                                  <code className="font-mono bg-yellow-900/30 px-1 rounded">
                                    seed-health-tenants.sh
                                  </code>{" "}
                                  to re-provision
                                </span>
                              </div>
                            )}
                            <div className="flex gap-2">
                              <span className="text-[var(--text-secondary)] w-32 shrink-0">
                                Profile ID
                              </span>
                              <span className="text-[var(--text-primary)] font-mono break-all">
                                {pp.id}
                              </span>
                            </div>
                            <div className="flex gap-2">
                              <span className="text-[var(--text-secondary)] w-32 shrink-0">
                                DID
                              </span>
                              <span className="text-[var(--text-primary)] font-mono break-all">
                                {did}
                              </span>
                            </div>
                            <div className="flex gap-2">
                              <span className="text-[var(--text-secondary)] w-32 shrink-0">
                                Participant Ctx
                              </span>
                              <span className="text-[var(--text-primary)] font-mono">
                                {ctxId !== "—" ? (
                                  ctxId
                                ) : (
                                  <span className="text-[var(--text-secondary)]">
                                    none
                                  </span>
                                )}
                              </span>
                            </div>
                            {activeVpas.length > 0 && (
                              <div className="flex gap-2">
                                <span className="text-[var(--text-secondary)] w-32 shrink-0">
                                  Active VPAs
                                </span>
                                <span className="text-green-800 dark:text-green-400">
                                  {activeVpas
                                    .map((v) => v.type.replace("cfm.", ""))
                                    .join(", ")}
                                </span>
                              </div>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  ) : (
                    <p className="text-[var(--text-secondary)] text-sm">
                      No dataspace profiles linked yet.
                    </p>
                  )}
                </div>
 
                {/* Digital Credentials (VCs) */}
                <div className="p-6">
                  <div className="flex items-center justify-between mb-3">
                    <h2 className="font-semibold flex items-center gap-2">
                      <ShieldCheck
                        size={16}
                        className="text-teal-800 dark:text-teal-300"
                      />
                      Digital Credentials
                    </h2>
                    <button
                      onClick={() => selected && loadCredentials(selected.id)}
                      disabled={credsLoading}
                      className="text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)] flex items-center gap-1 disabled:opacity-40"
                    >
                      <RefreshCw
                        size={11}
                        className={credsLoading ? "animate-spin" : ""}
                      />
                      Refresh
                    </button>
                  </div>
 
                  {credsLoading ? (
                    <div className="flex items-center gap-2 text-[var(--text-secondary)] text-sm">
                      <Loader2 size={13} className="animate-spin" />
                      Fetching credentials…
                    </div>
                  ) : credentials.length === 0 ||
                    credentials.every((c) => c.credentials.length === 0) ? (
                    <div className="rounded-lg bg-[var(--surface-2)]/40 border border-[var(--border)] p-4 text-sm">
                      <div className="flex items-center gap-2 text-yellow-800 dark:text-yellow-400 mb-2">
                        <ShieldOff size={14} />
                        <span className="font-medium">
                          No credentials issued yet
                        </span>
                      </div>
                      <p className="text-[var(--text-secondary)] text-xs leading-relaxed">
                        Verifiable Credentials (EHDS-compliant VCs) are issued
                        by the HDAB after participant onboarding via the
                        IdentityHub. To issue credentials, run:
                      </p>
                      <code className="mt-2 block text-xs text-[var(--success-text)] bg-[var(--surface)] rounded px-3 py-2">
                        bash jad/issue-ehds-credentials.sh
                      </code>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {credentials.flatMap((ctx) =>
                        ctx.credentials.map((vc, i) => {
                          const types = (vc.type || []).filter(
                            (t) => t !== "VerifiableCredential",
                          );
                          const expired =
                            vc.expirationDate &&
                            new Date(vc.expirationDate) < new Date();
                          return (
                            <div
                              key={`${ctx.profileId}-${i}`}
                              className={`p-3 rounded-lg border text-xs space-y-1.5 ${
                                expired
                                  ? "bg-red-100 dark:bg-red-950/30 border-red-300 dark:border-red-800/50"
                                  : "bg-green-100 dark:bg-green-950/20 border-green-300 dark:border-green-800/40"
                              }`}
                            >
                              <div className="flex items-center gap-1.5 mb-1">
                                {expired ? (
                                  <ShieldOff
                                    size={12}
                                    className="text-red-800 dark:text-red-400"
                                  />
                                ) : (
                                  <ShieldCheck
                                    size={12}
                                    className="text-green-800 dark:text-green-400"
                                  />
                                )}
                                <span
                                  className={
                                    expired
                                      ? "text-red-800 dark:text-red-400"
                                      : "text-green-800 dark:text-green-400"
                                  }
                                >
                                  {types.join(", ") || "VerifiableCredential"}
                                </span>
                                {expired && (
                                  <span className="text-red-800 dark:text-red-400 ml-auto">
                                    EXPIRED
                                  </span>
                                )}
                              </div>
                              <div className="flex gap-2">
                                <span className="text-[var(--text-secondary)] w-28 shrink-0">
                                  Issuer
                                </span>
                                <span className="text-[var(--text-primary)] font-mono break-all">
                                  {vc.issuer || "—"}
                                </span>
                              </div>
                              <div className="flex gap-2">
                                <span className="text-[var(--text-secondary)] w-28 shrink-0">
                                  Issued
                                </span>
                                <span className="text-[var(--text-primary)]">
                                  {vc.issuanceDate
                                    ? new Date(
                                        vc.issuanceDate,
                                      ).toLocaleDateString()
                                    : "—"}
                                </span>
                              </div>
                              {vc.expirationDate && (
                                <div className="flex gap-2">
                                  <span className="text-[var(--text-secondary)] w-28 shrink-0">
                                    Expires
                                  </span>
                                  <span
                                    className={
                                      expired
                                        ? "text-red-800 dark:text-red-400"
                                        : "text-[var(--text-primary)]"
                                    }
                                  >
                                    {new Date(
                                      vc.expirationDate,
                                    ).toLocaleDateString()}
                                  </span>
                                </div>
                              )}
                              {vc.id && (
                                <div className="flex gap-2">
                                  <span className="text-[var(--text-secondary)] w-28 shrink-0">
                                    Credential ID
                                  </span>
                                  <span className="text-[var(--text-secondary)] font-mono text-[10px] break-all">
                                    {vc.id}
                                  </span>
                                </div>
                              )}
                            </div>
                          );
                        }),
                      )}
                    </div>
                  )}
                </div>
 
                {/* Save */}
                <div className="p-6 flex items-center gap-3">
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="flex items-center gap-2 px-4 py-2 bg-[var(--accent)] text-white dark:text-gray-900 rounded-lg text-sm font-medium hover:bg-[var(--accent-hover)] disabled:opacity-50"
                  >
                    {saving ? (
                      <>
                        <Loader2 size={16} className="animate-spin" />
                        Saving…
                      </>
                    ) : saved ? (
                      <>
                        <CheckCircle2 size={16} />
                        Saved
                      </>
                    ) : (
                      <>
                        <Save size={16} />
                        Save Changes
                      </>
                    )}
                  </button>
                  {saveError && (
                    <span className="text-xs text-[var(--danger-text)] flex items-center gap-1">
                      <AlertCircle size={12} />
                      {saveError}
                    </span>
                  )}
                  {saved && !saveError && (
                    <span className="text-xs text-green-500">
                      Profile saved successfully.
                    </span>
                  )}
                </div>
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}