All files / src/components HealthDetailModal.tsx

90.9% Statements 40/44
64.7% Branches 22/34
84.61% Functions 11/13
90% Lines 36/40

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 3112x                                                                   2x                     15x                     15x 15x 15x 15x   15x 15x       15x         15x                                     8x 8x 8x 8x 8x 8x 4x 1x   4x 4x 4x 4x 4x 4x       8x   4x                                                                                                         9x 9x 9x 9x 9x                                                                                                                                                           15x                                         15x 15x                               21x                                                      
"use client";
 
/**
 * HealthDetailModal — the clickable detail view for a personal-health dashboard
 * card (fitness / labs / nutrition). Shows ~3-month weekly trends (TrendChart)
 * with an improving/declining chip, plus the weekly plan for nutrition.
 * Synthetic, illustrative data from journey-config, or the person's own
 * values for a record Klarbefund created (lib/patient/own-health.ts), whose
 * series carry their own period and a neutral chip.
 */
import { useEffect, useState } from "react";
import { createPortal } from "react-dom";
import {
  X,
  TrendingUp,
  TrendingDown,
  CalendarDays,
  Target,
  Check,
  Leaf,
  Wheat,
  Drumstick,
} from "lucide-react";
import { TrendChart } from "@/components/charts/TrendChart";
import { useT } from "@/lib/i18n/translate";
import { useLanguage } from "@/lib/use-language";
import type { CatalogLanguage } from "@/lib/metadata-language";
import type {
  PersonalHealthSource,
  TrendSeries,
  WeeklyGoal,
} from "@/lib/journey-config";
 
/** Maps a weekly-goal icon key to its lucide glyph. */
const GOAL_ICON: Record<WeeklyGoal["icon"], typeof Leaf> = {
  plants: Leaf,
  fibre: Wheat,
  protein: Drumstick,
};
 
/** A trend's own period when it has one, as its two days ("12 Jul 2026"). */
function period(
  s: TrendSeries,
  lang: CatalogLanguage,
): { from: string; to: string } | null {
  Eif (!s.from || !s.to) return null;
  const day = (iso: string) =>
    new Date(iso).toLocaleDateString(lang === "en" ? "en-GB" : lang, {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  return { from: day(s.from), to: day(s.to) };
}
 
function deltaChip(s: TrendSeries, threeMonths: string) {
  const first = s.points[0];
  const last = s.points[s.points.length - 1];
  const rising = last >= first;
  const improving = rising === (s.goodDirection === "up");
  const pct =
    first === 0 ? 0 : Math.round(((last - first) / Math.abs(first)) * 100);
  const Icon = rising ? TrendingUp : TrendingDown;
  // A person's own values move; whether that is good is not the portal's to
  // say, so a neutral series gets no green or orange.
  const colour =
    s.goodDirection === "neutral"
      ? "#6B7280"
      : improving
        ? "#1E8449"
        : "#CA6F1E";
  return (
    <span
      className="inline-flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full"
      style={{ color: colour, background: `${colour}1a` }}
    >
      <Icon size={12} />
      {pct > 0 ? "+" : ""}
      {pct}%{s.from ? "" : ` · ${threeMonths}`}
    </span>
  );
}
 
export function HealthDetailModal({
  source,
  onClose,
}: {
  source: PersonalHealthSource;
  onClose: () => void;
}) {
  const t = useT("patient");
  const tc = useT("common");
  const lang = useLanguage();
  const [mounted, setMounted] = useState(false);
  useEffect(() => setMounted(true), []);
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      Eif (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);
 
  if (!mounted) return null;
 
  return createPortal(
    <div
      role="dialog"
      aria-modal="true"
      aria-label={t("{title} detail", { title: t(source.title) })}
      className="fixed inset-0 z-100 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div className="absolute inset-0 bg-black/75 backdrop-blur-md" />
      <div
        className="relative z-10 w-full max-w-2xl rounded-2xl border-2 border-(--border) bg-(--surface) ring-1 ring-black/10 shadow-[0_24px_70px_rgba(0,0,0,0.45)] p-6 sm:p-8 max-h-[92vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          type="button"
          onClick={onClose}
          aria-label={tc("Close")}
          className="absolute top-3 right-3 grid place-items-center w-9 h-9 rounded-full text-(--text-secondary) hover:bg-(--surface-2) transition-colors"
        >
          <X size={18} />
        </button>
 
        <div className="flex items-center gap-3 mb-1 pr-8">
          <span
            className="w-2.5 h-8 rounded-full shrink-0"
            style={{ background: source.brand }}
          />
          <div>
            <h2 className="text-xl font-extrabold text-(--text-primary) leading-tight">
              {t(source.title)}
            </h2>
            <p className="text-xs text-(--text-secondary)">
              {t(source.source)}
            </p>
          </div>
        </div>
        <p className="text-sm text-(--text-secondary) mb-5">
          {t(source.detail)}
        </p>
 
        {/* Weekly nutrition goals — plant diversity / fibre / protein */}
        {source.weeklyGoals && (
          <div className="mb-5">
            <p className="flex items-center gap-1.5 text-sm font-bold text-(--text-primary) mb-2">
              <Target
                size={15}
                aria-hidden="true"
                style={{ color: source.brand }}
              />
              {t("Weekly goals")}
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
              {source.weeklyGoals.map((g) => {
                const Icon = GOAL_ICON[g.icon];
                const met = g.current >= g.target;
                const ratio = Math.min(1, g.current / g.target);
                const accent = met ? "#1E8449" : "#CA6F1E";
                return (
                  <div
                    key={g.label}
                    className="rounded-xl border border-(--border) bg-(--surface-2) p-3"
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className="inline-flex items-center gap-1.5 text-xs font-bold text-(--text-primary)">
                        <Icon
                          size={14}
                          aria-hidden="true"
                          style={{ color: accent }}
                        />
                        {t(g.label)}
                      </span>
                      {/* Status chip in BOTH states — text cue, not colour alone (WCAG 1.4.1) */}
                      <span
                        className="inline-flex items-center gap-0.5 text-[10px] font-semibold px-1.5 py-0.5 rounded-full whitespace-nowrap"
                        style={{ color: accent, background: `${accent}1a` }}
                      >
                        {met ? (
                          <>
                            <Check size={10} aria-hidden="true" /> {t("met")}
                          </>
                        ) : (
                          t("{n} to go", { n: g.target - g.current })
                        )}
                      </span>
                    </div>
                    <div className="flex items-baseline gap-1">
                      <span className="text-lg font-black text-(--text-primary) tabular-nums">
                        {g.current}
                      </span>
                      <span className="text-xs text-(--text-secondary)">
                        / {g.target} {t(g.unit)}
                      </span>
                    </div>
                    <div
                      role="progressbar"
                      aria-valuenow={Math.min(g.current, g.target)}
                      aria-valuemin={0}
                      aria-valuemax={g.target}
                      aria-valuetext={t("{current} of {target} {unit}", {
                        current: g.current,
                        target: g.target,
                        unit: t(g.unit),
                      })}
                      aria-label={`${t(g.label)}: ${t(
                        "{current} of {target} {unit}",
                        {
                          current: g.current,
                          target: g.target,
                          unit: t(g.unit),
                        },
                      )}, ${
                        met
                          ? t("goal met")
                          : t("{n} to go", { n: g.target - g.current })
                      }`}
                      className="h-1.5 rounded-full bg-(--border) mt-2 overflow-hidden"
                    >
                      <div
                        className="h-full rounded-full transition-all"
                        style={{ width: `${ratio * 100}%`, background: accent }}
                      />
                    </div>
                    <p className="text-[10px] text-(--text-secondary) mt-1">
                      {t(g.note)}
                    </p>
                  </div>
                );
              })}
            </div>
          </div>
        )}
 
        {/* 3-month weekly trends */}
        <div className="space-y-4">
          {source.trends.map((s) => (
            <div
              key={s.label}
              className="rounded-xl border border-(--border) bg-(--surface-2) p-4"
            >
              <div className="flex items-baseline justify-between gap-3 mb-2">
                <div className="flex items-baseline gap-2">
                  <span className="text-sm font-bold text-(--text-primary)">
                    {t(s.label)}
                  </span>
                  <span className="text-lg font-black text-(--text-primary)">
                    {s.current}
                  </span>
                  <span className="text-xs text-(--text-secondary)">
                    {t(s.unit)}
                  </span>
                </div>
                {deltaChip(s, t("3 mo"))}
              </div>
              <TrendChart points={s.points} color={s.color} />
              <p className="text-[10px] text-(--text-secondary) mt-1 text-right">
                {(() => {
                  const p = period(s, lang);
                  return p ? t("{from} to {to}", p) : t("last 12 weeks");
                })()}
              </p>
            </div>
          ))}
        </div>
 
        {/* Nutrition weekly plan */}
        {source.weeklyPlan && (
          <div className="mt-5">
            <p className="flex items-center gap-1.5 text-sm font-bold text-(--text-primary) mb-2">
              <CalendarDays size={15} style={{ color: source.brand }} />
              {t("This week’s plan")}
            </p>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
              {source.weeklyPlan.map((d) => (
                <div
                  key={d.day}
                  className="flex items-center justify-between gap-3 rounded-lg border border-(--border) bg-(--surface-2) px-3 py-2"
                >
                  <span className="text-xs font-bold text-(--text-primary) w-9 shrink-0">
                    {t(d.day)}
                  </span>
                  <span className="text-xs text-(--text-secondary) flex-1 truncate">
                    {t(d.focus)}
                  </span>
                  <span className="text-xs font-semibold text-(--text-primary) tabular-nums">
                    {d.kcal.toLocaleString()} kcal
                  </span>
                </div>
              ))}
            </div>
          </div>
        )}
 
        <p className="text-[11px] text-(--text-secondary) mt-5 text-center">
          {t("Synthetic · illustrative · not medical advice.")}
        </p>
      </div>
    </div>,
    document.body,
  );
}