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 | 1x 1x 66x 1x 4x 4x 4x 4x 4x 13x 32x 32x 32x 32x 32x 15x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 32x 11x 8x 8x 8x 8x 8x 8x 8x 8x 8x 3x 8x 1x 1x 32x 15x 1x 1x 1x 1x 1x 1x 32x 32x 13x 32x 32x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 15x 15x 32x 8x 1x 26x 1x 1x 1x | "use client";
import Link from "next/link";
import { fetchApi } from "@/lib/api";
import { formatEhrSync, type EhrSync } from "@/lib/patient/ehr-sync";
import { ownHealthSources, type OwnHealth } from "@/lib/patient/own-health";
import { useEffect, useMemo, useState, type CSSProperties } from "react";
import { T, useT } from "@/lib/i18n/translate";
import { useLanguage } from "@/lib/use-language";
import {
Activity,
Heart,
Stethoscope,
FlaskConical,
Pill,
Scissors,
Users,
Salad,
ScanLine,
ShieldCheck,
ArrowRight,
Sparkles,
Syringe,
type LucideIcon,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import { SignInRequired } from "@/components/SignInRequired";
import { RegisterDialog } from "@/components/RegisterDialog";
import { HealthDetailModal } from "@/components/HealthDetailModal";
import {
personalHealth,
insurer,
type PersonalHealthSource,
} from "@/lib/journey-config";
import {
accessibleBrandText,
brandBackgroundForWhiteText,
} from "@/lib/accessible-color";
interface PatientListItem {
id: string;
name: string;
gender: string;
birthDate: string;
/** the patient's own record carries an age, never a birth date (#475) */
age?: number | null;
}
interface CohortStats {
patients: number;
encounters: number;
conditions: number;
observations: number;
medications: number;
procedures: number;
}
interface TimelineEntry {
fhirType: string;
fhirId: string;
date: string;
display: string;
/** An Observation's value and unit (absent in older mock fixtures). */
value?: string | null;
unit?: string | null;
omopType: string;
omopId: string;
}
/* WCAG-safe FHIR type colours — ≥4.5:1 on white (light) and on #0b1326 (dark) */
const FHIR_TYPE_TOKENS: Record<
string,
{ text: string; bg: string; icon: React.ReactNode }
> = {
Encounter: {
text: "var(--fhir-encounter)",
bg: "var(--role-holder-bg)",
icon: <Stethoscope size={12} />,
},
Condition: {
text: "var(--fhir-condition)",
bg: "var(--role-user-bg)",
icon: <Activity size={12} />,
},
Observation: {
text: "var(--fhir-observation)",
bg: "var(--role-user-bg)",
icon: <FlaskConical size={12} />,
},
MedicationRequest: {
text: "var(--fhir-medication)",
bg: "var(--role-hdab-bg)",
icon: <Pill size={12} />,
},
Procedure: {
text: "var(--fhir-procedure)",
bg: "var(--role-trust-bg)",
icon: <Scissors size={12} />,
},
Immunization: {
text: "var(--fhir-encounter)",
bg: "var(--role-holder-bg)",
icon: <Syringe size={12} />,
},
};
/* Metric orb stat card — Stitch patient_dashboard_day pattern */
function MetricCard({
label,
value,
isOrb = false,
icon,
sub,
}: {
label: string;
value?: number;
isOrb?: boolean;
icon: React.ReactNode;
sub?: string;
}) {
return (
// Icon above the label until the card is wide enough to sit beside it,
// so a label such as "Observations" never breaks inside the word.
<div className="surface-card p-5 flex flex-col-reverse justify-end items-start gap-3 lg:flex-row lg:justify-between border border-(--border)">
<div className="min-w-0 lg:flex-1">
<p className="section-label mb-1">{label}</p>
<p className="text-3xl font-black text-(--text-primary) leading-none tracking-tight">
{value != null ? value.toLocaleString() : "—"}
</p>
{sub && <p className="text-xs text-(--text-secondary) mt-1">{sub}</p>}
</div>
{isOrb ? (
<div className="metric-orb">{icon}</div>
) : (
<div className="icon-orb">{icon}</div>
)}
</div>
);
}
/* Personal-health source icon per id (data lives in journey-config). */
const HEALTH_ICON: Record<PersonalHealthSource["id"], LucideIcon> = {
fitness: Activity,
labs: FlaskConical,
nutrition: Salad,
};
/**
* A patient's own health-data source card (fitness / labs / nutrition). Under
* NEXT_PUBLIC_DEMO_TK it shows the git-ignored personal screenshot; the public
* default shows a brand-tinted icon header with generic, fictional source labels.
*/
function PersonalHealthCard({
s,
onOpen,
}: {
s: PersonalHealthSource;
onOpen: () => void;
}) {
const [imgOk, setImgOk] = useState(true);
const t = useT("patient");
const Icon = HEALTH_ICON[s.id];
// Brand accents fail WCAG AA as small text, so derive theme-aware,
// contrast-safe variants for the "View 3-month trends" CTA.
const brandText = accessibleBrandText(s.brand);
return (
<button
type="button"
onClick={onOpen}
aria-label={t("{title}: view 3-month trends", { title: t(s.title) })}
className="surface-card border border-(--border) rounded-xl overflow-hidden text-left w-full transition-all hover:border-(--accent) hover:shadow-md focus:outline-hidden focus-visible:ring-2 focus-visible:ring-(--accent)"
>
{s.screenshot && imgOk ? (
<div className="h-24 bg-white relative">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={s.screenshot}
alt={t("{source} (real screenshot)", { source: t(s.source) })}
onError={() => setImgOk(false)}
className="w-full h-full object-cover object-top"
/>
<span
className="absolute top-1.5 left-1.5 text-[10px] font-bold px-2 py-0.5 rounded-full text-white"
style={{ background: brandBackgroundForWhiteText(s.brand) }}
>
{t(s.source)}
</span>
</div>
) : null}
<div className="p-4">
<div className="flex items-center gap-2 mb-3">
<span
className="grid place-items-center w-8 h-8 rounded-lg text-white shrink-0"
style={{ background: s.brand }}
>
<Icon size={16} />
</span>
<div className="min-w-0">
<p className="text-sm font-bold text-(--text-primary) truncate">
{t(s.title)}
</p>
<p className="text-[11px] text-(--text-secondary) truncate">
{t(s.source)}
</p>
</div>
</div>
<div className="grid grid-cols-2 gap-2">
{s.metrics.map((m) => (
<div
key={m.label}
className="rounded-lg bg-(--surface-2) px-2.5 py-1.5"
>
<p className="text-[10px] text-(--text-secondary) uppercase tracking-wide">
{t(m.label)}
</p>
<p className="text-sm font-bold text-(--text-primary)">
{m.value}
</p>
</div>
))}
</div>
<p
className="mt-3 flex items-center gap-1 text-xs font-semibold text-(--brand-l) dark:text-(--brand-d)"
style={
{
"--brand-l": brandText.light,
"--brand-d": brandText.dark,
} as CSSProperties
}
>
{s.trends[0]?.from ? t("View trends") : t("View 3-month trends")}{" "}
<ArrowRight size={13} />
</p>
</div>
</button>
);
}
export default function PatientPage() {
const t = useT("patient");
const tn = useT("nav");
const tc = useT("common");
const lang = useLanguage();
// FHIR's administrative gender codes, in the picked language.
const gender = (g: string | null | undefined) =>
g === "female"
? t("female")
: g === "male"
? t("male")
: g === "other"
? t("other")
: g === "unknown"
? t("unknown")
: g;
const [patients, setPatients] = useState<PatientListItem[]>([]);
const [ehrModal, setEhrModal] = useState(false);
const [ehrReceived, setEhrReceived] = useState(false);
const [lastEhrSync, setLastEhrSync] = useState<EhrSync | null>(null);
/** The person's own values, when the record is one Klarbefund created. */
const [ownHealth, setOwnHealth] = useState<OwnHealth | null>(null);
const [detailSource, setDetailSource] = useState<PersonalHealthSource | null>(
null,
);
const [stats, setStats] = useState<CohortStats | null>(null);
const [selected, setSelected] = useState<string>("");
const [timeline, setTimeline] = useState<TimelineEntry[]>([]);
const [loading, setLoading] = useState(true);
const [restricted, setRestricted] = useState(false);
const [unauthenticated, setUnauthenticated] = useState(false);
useEffect(() => {
fetchApi("/api/patient")
.then(async (r) => {
Iif (r.status === 401) throw new Error("UNAUTHENTICATED");
return r.json();
})
.then((d) => {
setPatients(d.patients ?? []);
setStats(d.stats ?? null);
setRestricted(d.restricted === true);
// The restricted (own-record) response embeds the patient's timeline.
if (Array.isArray(d.timeline)) setTimeline(d.timeline);
setLastEhrSync(d.lastEhrSync ?? null);
setOwnHealth(d.ownHealth ?? null);
if (d.restricted && d.patients?.length === 1) {
setSelected(d.patients[0].id);
}
setLoading(false);
})
.catch((e: Error) => {
Iif (e.message === "UNAUTHENTICATED") setUnauthenticated(true);
setLoading(false);
});
}, []);
useEffect(() => {
// Restricted (own-record) patients already have their timeline embedded in
// the /api/patient response — don't refetch (and overwrite) it.
if (!selected || restricted) return;
setLoading(true);
fetchApi(`/api/patient?patientId=${encodeURIComponent(selected)}`)
.then(async (r) => {
Iif (r.status === 401) throw new Error("UNAUTHENTICATED");
return r.json();
})
.then((d) => {
setTimeline(d.timeline ?? []);
setLoading(false);
})
.catch((e: Error) => {
if (e.message === "UNAUTHENTICATED") setUnauthenticated(true);
setLoading(false);
});
}, [selected, restricted]);
const selectedPatient = patients.find((p) => p.id === selected);
const healthCards = useMemo(
() => (ownHealth ? ownHealthSources(ownHealth) : personalHealth),
[ownHealth],
);
/* The "Request EHR data" flow just completed: stamp the sync on the own
record. Without a record of our own (or in the static demo) the moment
the flow completed is the sync time. */
const recordEhrSync = () => {
const now = new Date().toISOString();
fetchApi("/api/patient/ehr-sync", { method: "POST" })
.then(async (r) => (r.ok ? r.json() : null))
.then((d) => {
setLastEhrSync(d?.lastEhrSync ?? { at: now, source: null });
})
.catch(() => setLastEhrSync({ at: now, source: null }));
};
/* Group timeline entries by year+month, newest first. Events within each
month are also sorted newest first so the reader scans most recent → oldest. */
const timelineGroups = useMemo(() => {
const dated = timeline.filter((e) => !!e.date);
const undated = timeline.filter((e) => !e.date);
dated.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
const groups: { key: string; label: string; items: TimelineEntry[] }[] = [];
for (const entry of dated) {
const d = new Date(entry.date);
Iif (Number.isNaN(d.getTime())) continue;
const key = `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(
2,
"0",
)}`;
const existing = groups.find((g) => g.key === key);
Iif (existing) {
existing.items.push(entry);
} else {
groups.push({
key,
label: d.toLocaleString(lang === "en" ? "en-US" : lang, {
month: "long",
year: "numeric",
timeZone: "UTC",
}),
items: [entry],
});
}
}
Iif (undated.length) {
groups.push({ key: "undated", label: t("Undated"), items: undated });
}
return groups;
// t follows lang, which is in the dependencies.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timeline, lang]);
return (
<div className="min-h-screen bg-(--bg)">
<div className="max-w-4xl mx-auto px-6 py-10">
<PageIntro
title={tn("Patient Journey")}
icon={Activity}
description={t(
"View individual FHIR R4 clinical events mapped to OMOP CDM concepts. Select a patient to see their encounters, conditions, observations, medications, and procedures in chronological order.",
)}
prevStep={{ href: "/catalog", label: tn("Dataset Catalog") }}
nextStep={{ href: "/analytics", label: tn("OMOP Analytics") }}
infoText={t(
"Patient data is generated by Synthea and loaded into Neo4j as FHIR R4 resources. The OMOP CDM mapping (Layer 4) enables cross-site cohort analysis under EHDS Art. 53.",
)}
docLink={{
href: "/docs/architecture",
label: t("Architecture Docs"),
}}
/>
{/* ── My personal health record (identity + Request EHR) ──────────── */}
{/* Only on the own record: every other role browses the cohort and
has no personal record, so it must not see the patient persona's
values or a selected patient's name as "my record". */}
{restricted && (
<section className="mb-8">
<div className="flex items-start justify-between gap-3 mb-4 flex-wrap">
<div className="flex items-center gap-3">
<span
className="grid place-items-center w-12 h-12 rounded-full text-white shrink-0"
style={{ background: "var(--role-patient-text)" }}
>
<Heart size={22} />
</span>
<div>
<h2 className="text-xl font-extrabold text-(--text-primary) leading-tight">
{selectedPatient?.name ?? t("My personal health record")}
</h2>
<p className="text-xs text-(--text-secondary)">
{selectedPatient ? (
<>
<span className="capitalize">
{gender(selectedPatient.gender)}
</span>
{selectedPatient.age != null
? ` · ${t("age {age}", { age: selectedPatient.age })}`
: selectedPatient.birthDate
? ` · ${t("born {date}", {
date: selectedPatient.birthDate,
})}`
: ""}
{" · "}
{timeline.length === 1
? t("{n} event on record", { n: timeline.length })
: t("{n} events on record", { n: timeline.length })}
</>
) : (
t(
"My own fitness, lab and nutrition data, plus my ePA on request.",
)
)}
</p>
{/* Only once the record is known: a sync, or none yet on the
own record. Other roles have no record of their own. */}
{!loading && (lastEhrSync || restricted) && (
<p
className="text-xs text-(--text-secondary) mt-0.5"
data-testid="last-ehr-sync"
>
{lastEhrSync ? (
<>
{t("Last EHR sync:")}{" "}
<time
dateTime={lastEhrSync.at}
className="font-semibold text-(--text-primary)"
>
{formatEhrSync(
lastEhrSync.at,
lang === "en" ? undefined : lang,
)}
</time>
{lastEhrSync.source
? ` · ${t(lastEhrSync.source)}`
: ""}
</>
) : (
t(
"No EHR sync yet: your ePA has not been transferred into the portal.",
)
)}
</p>
)}
</div>
</div>
<button
type="button"
onClick={() => setEhrModal(true)}
className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-white text-sm font-semibold shadow-xs transition-all hover:scale-[1.02] shrink-0"
style={{
background: brandBackgroundForWhiteText(insurer.brand),
}}
>
<ScanLine size={16} aria-hidden="true" />
{ehrReceived
? t("Request more EHR data")
: t("Request EHR data")}
</button>
</div>
{ehrReceived && (
<div className="mb-4 px-4 py-3 rounded-xl border border-(--role-holder-border) bg-(--role-holder-bg) text-sm text-(--role-holder-text) flex items-start gap-2">
<ShieldCheck size={16} className="mt-0.5 shrink-0" />
<span>
<T
area="patient"
vars={{ insurer: insurer.name, short: insurer.short }}
tags={{ b: <strong className="font-semibold" /> }}
>
{
"Your ePA from <b>{insurer}</b> was transferred into the portal as FHIR R4: GesundheitsID-authenticated, end-to-end encrypted. {short} cannot read it; withdraw any time."
}
</T>
</span>
</div>
)}
{/* A record Klarbefund created shows the person's own values; a demo
persona keeps the illustration of journey-config. */}
{ownHealth && healthCards.length === 0 && (
<p
className="mb-4 text-sm text-(--text-secondary)"
data-testid="own-health-empty"
>
{t(
"No values from your devices or reports yet. In Klarbefund, switch on sending your reports and your device trends to your record.",
)}
</p>
)}
<div
className="grid sm:grid-cols-3 gap-4"
data-testid="health-cards"
>
{healthCards.map((s) => (
<PersonalHealthCard
key={s.id}
s={s}
onOpen={() => setDetailSource(s)}
/>
))}
</div>
<Link
href="/patient/query"
className="mt-4 inline-flex items-center gap-2 text-sm font-semibold text-(--accent) hover:underline"
>
<Sparkles size={16} aria-hidden="true" />
{t("Ask research questions about my own data")}
<ArrowRight size={14} aria-hidden="true" />
</Link>
</section>
)}
{detailSource && (
<HealthDetailModal
source={detailSource}
onClose={() => setDetailSource(null)}
/>
)}
{ehrModal && (
<RegisterDialog
mode="ehr"
title={t("Request your ePA from {insurer}", {
insurer: insurer.name,
})}
subtitle={t(
"Scan with your insurer app, or approve on the simulated phone, authorised via GesundheitsID. The insurer cannot read the encrypted contents.",
)}
onClose={() => setEhrModal(false)}
onComplete={() => {
setEhrModal(false);
setEhrReceived(true);
recordEhrSync();
}}
/>
)}
{unauthenticated ? (
<SignInRequired
description={t(
"The Patient Journey view is restricted to authenticated users. Sign in with one of the demo personas to explore FHIR R4 clinical timelines mapped to OMOP CDM concepts.",
)}
/>
) : (
<>
{/* Cohort metric orb cards — Stitch patient_dashboard_day bento */}
{stats && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-4 mb-8">
<MetricCard
label={t("Patients")}
value={stats.patients}
isOrb
icon={<Heart size={20} className="text-white" />}
sub={restricted ? t("Your record") : t("Synthea cohort")}
/>
<MetricCard
label={t("Encounters")}
value={stats.encounters}
icon={<Stethoscope size={18} />}
/>
<MetricCard
label={t("Conditions")}
value={stats.conditions}
icon={<Activity size={18} />}
/>
<MetricCard
label={t("Observations")}
value={stats.observations}
icon={<FlaskConical size={18} />}
/>
<MetricCard
label={t("Medications")}
value={stats.medications}
icon={<Pill size={18} />}
/>
<MetricCard
label={t("Procedures")}
value={stats.procedures}
icon={<Scissors size={18} />}
/>
</div>
)}
{/* Patient selector */}
{restricted ? (
<div className="mb-4 px-4 py-3 bg-(--role-patient-bg) border border-(--role-patient-border) rounded-xl text-sm text-(--role-patient-text) flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-(--role-patient-text) inline-block animate-pulse" />
{t(
"Showing your personal health record (EHDS Art. 3 / GDPR Art. 15)",
)}
</div>
) : (
<div className="mb-6">
<label className="section-label block">
{t("Select patient")}
<select
value={selected}
onChange={(e) => setSelected(e.target.value)}
className="mt-1 px-3 py-2.5 bg-(--surface-card) border border-(--border-ui) rounded-xl text-sm outline-hidden focus:border-(--accent) w-full text-(--text-primary) block"
>
<option value="">
{t("Select patient ({n} loaded)", { n: patients.length })}
</option>
{patients.map((p) => (
<option key={p.id} value={p.id}>
{p.name ?? p.id}
</option>
))}
</select>
</label>
</div>
)}
{/* Patient demographics header */}
{selectedPatient && (
<div className="surface-card p-4 mb-6 flex items-center gap-6 border border-(--border)">
<div className="metric-orb shrink-0">
<Users size={20} className="text-white" />
</div>
<div className="flex gap-6 flex-wrap text-sm">
<div>
<p className="section-label mb-0.5">{t("Name")}</p>
<p className="font-semibold text-(--text-primary)">
{selectedPatient.name ?? selectedPatient.id}
</p>
</div>
<div>
<p className="section-label mb-0.5">{t("Gender")}</p>
<p className="font-semibold text-(--text-primary)">
{gender(selectedPatient.gender) ?? "—"}
</p>
</div>
<div>
<p className="section-label mb-0.5">
{selectedPatient.age != null ? t("Age") : t("Born")}
</p>
<p className="font-semibold text-(--text-primary)">
{selectedPatient.age != null
? selectedPatient.age
: selectedPatient.birthDate ?? "—"}
</p>
</div>
<div>
<p className="section-label mb-0.5">{t("Events")}</p>
<p className="font-semibold text-(--text-primary)">
{timeline.length}
</p>
</div>
</div>
</div>
)}
{loading && (
<p className="text-(--text-secondary) text-sm">
{tc("Loading…")}
</p>
)}
{!loading && selected && timeline.length === 0 && (
<p className="text-(--text-secondary) text-sm">
{t("No timeline events found for this patient.")}
</p>
)}
{/* Clinical timeline — grouped by year+month, newest first */}
{timeline.length > 0 && (
<div>
<div className="flex items-baseline justify-between mb-4">
<p className="section-label">{t("Clinical timeline")}</p>
<p className="text-xs text-(--text-secondary)">
{t("Newest first")}
</p>
</div>
{timelineGroups.map((group) => (
<section key={group.key} className="mb-6 last:mb-0">
<h3 className="text-sm font-bold text-(--text-primary) mb-3 pb-1 border-b border-(--border) uppercase tracking-wider">
{group.label}
<span className="ml-2 text-xs font-normal text-(--text-secondary) normal-case tracking-normal">
{group.items.length === 1
? t("{n} event", { n: group.items.length })
: t("{n} events", { n: group.items.length })}
</span>
</h3>
<ol className="activity-timeline space-y-5 pl-8">
{group.items.map((e, i) => {
const token = FHIR_TYPE_TOKENS[e.fhirType];
return (
<li key={`${group.key}-${i}`} className="relative">
{/* Timeline dot */}
<span
className="absolute -left-7 top-1 w-3.5 h-3.5 rounded-full border-2 border-(--surface-card) z-10"
style={{
background:
token?.text ?? "var(--text-secondary)",
}}
/>
<div className="surface-card p-4 border border-(--border) hover:shadow-md transition-shadow">
<div className="flex items-start justify-between gap-3 mb-1">
<div className="flex items-center gap-2">
{/* FHIR type badge */}
<span
className="inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-full"
style={{
color:
token?.text ?? "var(--text-secondary)",
background:
token?.bg ?? "var(--surface-2)",
}}
>
{token?.icon}
{e.fhirType}
</span>
<span className="text-xs text-(--text-secondary)">
{e.date ?? "—"}
</span>
</div>
</div>
<p className="text-sm font-medium text-(--text-primary)">
{e.display || (
<span className="font-mono text-xs text-(--text-secondary)">
{e.fhirId}
</span>
)}
</p>
{e.value != null && e.value !== "" && (
<p
className="text-sm text-(--text-primary) mt-0.5 tabular-nums"
data-testid="timeline-value"
>
{e.value}
{e.unit ? ` ${e.unit}` : ""}
</p>
)}
{e.omopType && (
<p className="text-xs text-(--layer4-text) mt-1">
↳ OMOP {e.omopType}: {e.omopId}
</p>
)}
</div>
</li>
);
})}
</ol>
</section>
))}
</div>
)}
</>
)}
</div>
</div>
);
}
|