All files / src/app/patient/query page.tsx

96.29% Statements 26/27
78.57% Branches 22/28
100% Functions 12/12
100% Lines 25/25

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 2491x                                                             1x             1x                         11x 11x   11x 11x                 11x 11x     3x 3x 3x   3x           11x                                           2x 2x             2x                                     33x 33x       1x                                                     4x 4x                                                       6x           22x                     11x                                                                                      
"use client";
 
/**
 * Personal Research — a natural-language-query page over the patient's OWN data
 * (EHDS Art. 3 / GDPR Art. 15 primary use). The query box is at the top; type a
 * question (or tap a suggestion, which fills the box and submits) and the answer
 * — fitness/lab/nutrition trends PLUS relevant ePA events (infections, surgery,
 * vaccinations, diagnoses) — appears below, computed only from the patient's own
 * records. No LLM in the static demo: free text is keyword-matched. Synthetic.
 */
import { useState } from "react";
import {
  Sparkles,
  Activity,
  Salad,
  Wind,
  ShieldCheck,
  Send,
  Info,
  type LucideIcon,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import { useT } from "@/lib/i18n/translate";
import { MetricTrendRow } from "@/components/charts/MetricTrendRow";
import {
  personalResearchQA,
  matchPersonalResearch,
  eventMarkers,
  type ResearchQA,
} from "@/lib/personal-research";
 
const QA_ICON: Record<string, LucideIcon> = {
  sport: Activity,
  nutrition: Salad,
  breathing: Wind,
};
 
/** Badge colour per ePA event type. */
const EPA_TYPE_COLOR: Record<string, string> = {
  Infection: "#CA6F1E",
  Surgery: "#2471A3",
  Vaccination: "#1E8449",
  Diagnosis: "#7D3C98",
};
 
interface Exchange {
  question: string;
  qa: ResearchQA | null;
}
 
export default function PersonalQueryPage() {
  const t = useT("patient");
  const tn = useT("nav");
  // The ePA event types of lib/personal-research, by name.
  const eventType = (type: string) =>
    type === "Infection"
      ? t("Infection")
      : type === "Surgery"
        ? t("Surgery")
        : type === "Vaccination"
          ? t("Vaccination")
          : type === "Diagnosis"
            ? t("Diagnosis")
            : type;
  const [input, setInput] = useState("");
  const [exchanges, setExchanges] = useState<Exchange[]>([]);
 
  function send(text: string) {
    const q = text.trim();
    Iif (!q) return;
    setInput(q); // keep the query visible in the box
    // newest first — the latest answer shows directly under the field
    setExchanges((prev) => [
      { question: q, qa: matchPersonalResearch(q) },
      ...prev,
    ]);
  }
 
  return (
    <div className="min-h-screen bg-(--bg)">
      <div className="max-w-3xl mx-auto px-6 py-10">
        <PageIntro
          title={tn("Personal Research")}
          icon={Sparkles}
          description={t(
            "Ask a question about your own health data: fitness, lab and nutrition trends together with your ePA record (infections, surgeries, vaccinations and diagnoses). Answers are computed only from your own records (EHDS Art. 3 / GDPR Art. 15, primary use). Synthetic · illustrative · not medical advice.",
          )}
          prevStep={{ href: "/patient", label: tn("My Health Records") }}
          nextStep={{
            href: "/patient/insights",
            label: tn("Research Insights"),
          }}
          infoText={t(
            "This is primary use: you query your own data. It never leaves your record and is not compared against other patients. The static demo matches your free-text question to a predefined answer by keyword (no AI model).",
          )}
        />
 
        {/* Query box — at the top */}
        <form
          onSubmit={(e) => {
            e.preventDefault();
            send(input);
          }}
          className="flex items-center gap-2"
        >
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            aria-label={t("Ask a question about your own health data")}
            placeholder={t("Ask about your own health data…")}
            className="flex-1 rounded-xl border border-(--border-ui) bg-(--surface-card) px-4 py-3 text-sm text-(--text-primary) outline-hidden focus:border-(--accent)"
          />
          <button
            type="submit"
            disabled={!input.trim()}
            aria-label={t("Send question")}
            className="grid place-items-center w-12 h-12 rounded-xl text-white shrink-0 transition-all hover:scale-[1.03] disabled:opacity-40 disabled:hover:scale-100"
            style={{ background: "var(--accent)" }}
          >
            <Send size={18} />
          </button>
        </form>
 
        {/* Suggestions — click fills the box and submits */}
        <div className="flex flex-wrap gap-2 mt-3">
          {personalResearchQA.map((qa) => {
            const Icon = QA_ICON[qa.id] ?? Sparkles;
            return (
              <button
                key={qa.id}
                type="button"
                onClick={() => send(qa.question)}
                className="inline-flex items-center gap-2 text-left rounded-full border border-(--border) bg-(--surface-2) px-3 py-1.5 text-xs text-(--text-primary) hover:border-(--accent) transition-colors"
              >
                <Icon
                  size={13}
                  className="shrink-0 text-(--accent)"
                  aria-hidden="true"
                />
                {qa.question}
              </button>
            );
          })}
        </div>
        <p className="text-[11px] text-(--text-secondary) mt-2">
          {t("Your own records only · synthetic · not medical advice")}
        </p>
 
        {/* Answers — below the field, newest first */}
        <div className="space-y-4 mt-6">
          {exchanges.length === 0 && (
            <div className="text-center text-sm text-(--text-secondary) py-8 rounded-xl border border-dashed border-(--border)">
              {t(
                "Ask a question above, or tap a suggestion, to see an answer from your own data.",
              )}
            </div>
          )}
          {exchanges.map((x, i) => {
            const Icon = x.qa ? QA_ICON[x.qa.id] ?? Sparkles : Info;
            return (
              <div key={exchanges.length - i} className="space-y-2">
                {/* question */}
                <div className="flex justify-end">
                  <p className="max-w-[85%] rounded-2xl rounded-br-sm bg-(--accent) text-white px-4 py-2.5 text-sm">
                    {x.question}
                  </p>
                </div>
                {/* answer */}
                <div className="rounded-2xl rounded-bl-sm border border-(--border) bg-(--surface) p-4">
                  <div className="flex items-center gap-2 mb-2">
                    <span
                      className="grid place-items-center w-8 h-8 rounded-lg text-white shrink-0"
                      style={{ background: x.qa ? "#7D3C98" : "#64748b" }}
                    >
                      <Icon size={16} />
                    </span>
                    <span className="text-xs font-bold uppercase tracking-wide text-(--text-secondary)">
                      {t("Your data assistant")}
                    </span>
                  </div>
                  {x.qa ? (
                    <>
                      <p className="text-sm text-(--text-primary) leading-relaxed mb-3">
                        {x.qa.answer}
                      </p>
                      <div className="grid sm:grid-cols-2 gap-2.5">
                        {x.qa.trends.map((tr) => (
                          <MetricTrendRow
                            key={tr.label}
                            s={tr}
                            markers={eventMarkers(
                              tr,
                              x.qa!.events,
                              (type) => EPA_TYPE_COLOR[type] ?? "#7D3C98",
                            )}
                          />
                        ))}
                      </div>
                      {x.qa.events.length > 0 && (
                        <ul className="space-y-1.5 mt-2.5">
                          <li className="text-[10px] font-bold uppercase tracking-wide text-(--text-secondary)">
                            {t("Related ePA events · marked on the trends")}
                          </li>
                          {x.qa.events.map((e) => (
                            <li
                              key={e.label}
                              className="flex items-center gap-2.5 rounded-lg bg-(--surface-2) border border-(--border) px-3 py-2"
                            >
                              <span
                                className="text-[10px] font-bold px-2 py-0.5 rounded-full text-white shrink-0 w-[88px] text-center"
                                style={{
                                  background:
                                    EPA_TYPE_COLOR[e.type] ?? "#7D3C98",
                                }}
                              >
                                {eventType(e.type)}
                              </span>
                              <span className="text-xs font-mono text-(--text-secondary) shrink-0">
                                {e.date}
                              </span>
                              <span className="text-sm text-(--text-primary)">
                                {e.label}
                              </span>
                            </li>
                          ))}
                        </ul>
                      )}
                      <p className="flex items-center gap-1.5 text-[11px] text-(--text-secondary) mt-3">
                        <ShieldCheck size={12} /> {x.qa.source}
                      </p>
                    </>
                  ) : (
                    <p className="text-sm text-(--text-primary) leading-relaxed">
                      {t(
                        "I can only answer from your own fitness, lab, nutrition and ePA records. Try asking about your sport routine, your nutrition, or your breathing & respiratory history.",
                      )}
                    </p>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}