File size: 35,669 Bytes
c255149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f394214
 
 
 
c255149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f394214
 
 
 
 
 
 
 
c255149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f394214
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c255149
 
 
 
 
f394214
 
 
 
c255149
f394214
c255149
 
f394214
 
 
 
c255149
f394214
 
c255149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b10d40
c255149
 
 
 
 
 
 
5b10d40
 
 
 
 
 
 
 
 
 
 
 
 
 
c255149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cardiac Monitor · Dashboard</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  /* Design tokens mirror app/cardiac_monitor/lib/config/theme.dart */
  :root {
    --bg: #F2F4F7; --card: #FFFFFF; --text: #1A1D21; --text2: #6B7280; --text3: #9CA3AF;
    --surface: #F8F9FA; --divider: #E5E7EB; --accent: #0D9488; --grid: #EEF0F3;
    --shadow: 0 8px 20px rgba(0,0,0,.06); --dim: rgba(255,255,255,.75);
    --normal: #22C55E; --low: #84CC16; --moderate: #EAB308; --elevated: #F97316; --high: #EF4444;
    --playback: #7C3AED;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #0F1419; --card: #1A1F26; --text: #E8ECF0; --text2: #8B949E; --text3: #6B7280;
      --surface: #21262D; --divider: #2D333B; --accent: #14B8A6; --grid: #252B33;
      --shadow: 0 8px 20px rgba(0,0,0,.3); --dim: rgba(0,0,0,.6);
    }
  }
  * { box-sizing: border-box; }
  html, body { margin: 0; background: var(--bg); color: var(--text);
    font-family: "Plus Jakarta Sans", system-ui, -apple-system, "Segoe UI", sans-serif; }
  .hidden { display: none !important; }
  button, input, select { font: inherit; }

  /* ── Login ── */
  .login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
  .login-card { width: 100%; max-width: 380px; background: var(--card); border-radius: 24px;
    box-shadow: var(--shadow); padding: 32px 28px; }
  .logo { width: 56px; height: 56px; border-radius: 18px; display: grid; place-items: center;
    background: linear-gradient(90deg, #0D9488, #06B6D4); box-shadow: 0 6px 16px rgba(13,148,136,.35); }
  .login h1 { font-size: 24px; font-weight: 800; margin: 18px 0 4px; }
  .login p { color: var(--text2); font-size: 14px; margin: 0 0 22px; }
  .field { display: block; margin-bottom: 14px; }
  .field span { display: block; font-size: 12px; font-weight: 600; color: var(--text2); margin-bottom: 6px; }
  .field input { width: 100%; padding: 13px 16px; border-radius: 12px; border: 1px solid var(--divider);
    background: var(--surface); color: var(--text); outline: none; }
  .field input:focus { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
  .btn-primary { width: 100%; height: 52px; border: 0; border-radius: 14px; color: #fff; font-weight: 700;
    font-size: 16px; cursor: pointer; background: linear-gradient(90deg, #0D9488, #06B6D4);
    box-shadow: 0 6px 16px rgba(13,148,136,.35); }
  .btn-primary:disabled { opacity: .6; cursor: progress; }
  .error { color: var(--high); font-size: 13px; min-height: 18px; margin: 4px 0 10px; }
  .tabs { display: flex; gap: 4px; padding: 4px; border-radius: 14px; background: var(--surface); margin-bottom: 20px; }
  .tabs button { flex: 1; border: 0; padding: 10px 0; border-radius: 10px; background: none; color: var(--text2);
    font-size: 14px; font-weight: 600; cursor: pointer; }
  .tabs button[aria-selected="true"] { color: #fff; background: linear-gradient(90deg, #0D9488, #06B6D4); }

  /* ── Layout ── */
  .wrap { max-width: 1120px; margin: 0 auto; padding: 16px 16px 32px; }
  header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 16px; margin: 8px 0 24px; }
  .greet { flex: 1 1 260px; min-width: 0; }
  .greet h1 { font-size: 28px; font-weight: 800; margin: 0; line-height: 1.2; }
  .greet .date { color: var(--text2); font-size: 14px; font-weight: 500; margin-top: 4px; }
  .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; }
  .pill { display: inline-flex; align-items: center; gap: 8px; padding: 8px 14px; border-radius: 24px;
    background: var(--card); box-shadow: var(--shadow); font-size: 13px; font-weight: 600; color: var(--text2);
    white-space: nowrap; }
  .pill select { border: 0; background: transparent; color: var(--text); font-weight: 700; outline: none;
    max-width: 260px; cursor: pointer; }
  .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text3); flex: none; }
  .dot.live { background: var(--normal); box-shadow: 0 0 0 0 rgba(34,197,94,.6); animation: pulse 1.6s infinite; }
  @keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(34,197,94,.55); } 70% { box-shadow: 0 0 0 8px rgba(34,197,94,0); }
    100% { box-shadow: 0 0 0 0 rgba(34,197,94,0); } }
  .btn-ghost { border: 0; background: var(--card); box-shadow: var(--shadow); color: var(--text2);
    border-radius: 24px; padding: 8px 14px; font-weight: 600; font-size: 13px; cursor: pointer; }

  .grid { display: grid; gap: 20px; grid-template-columns: repeat(3, minmax(0, 1fr)); }
  .span-2 { grid-column: span 2; } .span-3 { grid-column: span 3; }
  @media (max-width: 860px) { .grid { grid-template-columns: minmax(0, 1fr); } .span-2, .span-3 { grid-column: auto; } }

  .card { background: var(--card); border-radius: 24px; box-shadow: var(--shadow); padding: 22px; min-width: 0; }
  .card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 12px; margin-bottom: 18px; }
  .card-head h2 { font-size: 16px; font-weight: 700; margin: 0; flex: 1 1 200px; min-width: 0; }
  .card-head .sub { display: block; font-size: 12px; font-weight: 500; color: var(--text3); margin-top: 2px; }
  .icon-box { width: 34px; height: 34px; border-radius: 12px; display: grid; place-items: center; flex: none; }
  .chip { display: inline-flex; align-items: center; gap: 6px; padding: 4px 9px; border-radius: 8px;
    font-size: 11px; font-weight: 700; white-space: nowrap; background: var(--surface); color: var(--text2); }

  /* ── Heart-rate card (VitalCard) ── */
  .vital { border-radius: 24px; padding: 20px; color: #fff; display: flex; flex-direction: column;
    background: linear-gradient(135deg, #FF6B6B, #EE5A24); box-shadow: 0 8px 16px rgba(255,107,107,.35); }
  .vital .top { display: flex; align-items: center; gap: 8px; font-size: 12px; font-weight: 600; opacity: .9; }
  .vital .top span { flex: 1; }
  .vital .status { font-style: normal; background: rgba(255,255,255,.2); border-radius: 8px; padding: 3px 8px; font-size: 10px; font-weight: 700; }
  .vital .big { text-align: center; font-size: 52px; font-weight: 800; line-height: 1; margin: 26px 0 6px; }
  .vital .unit { text-align: center; font-size: 14px; font-weight: 500; opacity: .75; }
  .vital .bar { height: 6px; border-radius: 4px; background: rgba(255,255,255,.2); margin-top: auto; overflow: hidden; }
  .vital .bar i { display: block; height: 100%; width: 0; background: #fff; border-radius: 4px; transition: width .6s ease; }
  .vital .foot { margin-top: 18px; }

  /* ── Risk card (RiskIndicator) ── */
  .risk-row { display: flex; align-items: flex-end; gap: 4px; }
  .risk-num { font-size: 52px; font-weight: 800; line-height: 1; transition: color .3s; }
  .risk-pct { font-size: 22px; font-weight: 600; opacity: .7; padding-bottom: 6px; }
  .risk-label { margin-left: auto; padding: 6px 14px; border-radius: 20px; font-size: 13px; font-weight: 700;
    text-transform: capitalize; }
  .risk-bar { position: relative; height: 10px; border-radius: 6px; margin-top: 18px; overflow: hidden;
    background: linear-gradient(90deg, #22C55E, #84CC16, #EAB308, #F97316, #EF4444); }
  .risk-bar i { position: absolute; top: 0; right: 0; bottom: 0; background: var(--dim); transition: width .6s ease; }
  .scale { display: flex; justify-content: space-between; color: var(--text3); font-size: 10px; font-weight: 500; margin-top: 8px; }
  .meta { color: var(--text2); font-size: 12px; margin-top: 14px; display: flex; flex-wrap: wrap; gap: 6px 14px; }
  .notice { margin-top: 14px; padding: 10px 12px; border-radius: 12px; font-size: 12.5px; font-weight: 500;
    background: rgba(234,179,8,.12); color: var(--text); border: 1px solid rgba(234,179,8,.35); }

  /* ── ECG card ── */
  .ecg-wrap { position: relative; height: 230px; }
  canvas { display: block; width: 100%; height: 100%; }
  .overlay { position: absolute; inset: 0; display: grid; place-items: center; text-align: center;
    color: var(--text2); font-size: 14px; font-weight: 600; pointer-events: none; }
  .overlay small { display: block; color: var(--text3); font-weight: 500; font-size: 12px; margin-top: 4px; }
  .live-badge { background: rgba(34,197,94,.12); color: var(--normal); }
  .playback-badge { background: rgba(124,58,237,.12); color: var(--playback); }
  .source { color: var(--playback); font-size: 12.5px; font-weight: 600; margin: -8px 0 12px; }

  /* ── Trend + status ── */
  .trend-wrap { height: 150px; }
  .status-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 12px; }
  .stat { display: flex; align-items: center; gap: 10px; min-width: 0; }
  .stat .icon-box { width: 38px; height: 38px; border-radius: 14px; background: var(--surface); color: var(--text3); }
  .stat.ok .icon-box { background: rgba(34,197,94,.1); color: var(--normal); }
  .stat.warn .icon-box { background: rgba(234,179,8,.14); color: var(--moderate); }
  .stat > div { min-width: 0; }
  .stat b { display: block; font-size: 12px; font-weight: 700; }
  .stat span { display: block; font-size: 11.5px; color: var(--text2); overflow-wrap: anywhere; }

  footer { color: var(--text3); font-size: 12px; text-align: center; margin-top: 28px; line-height: 1.5; }
</style>
</head>
<body>

<!-- ─────────────── Login ─────────────── -->
<section id="login" class="login hidden">
  <form id="login-form" class="login-card" autocomplete="on">
    <div class="logo" aria-hidden="true">
      <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h4l2-5 4 10 2-5h6"/></svg>
    </div>
    <h1>Cardiac Monitor</h1>
    <p>Real-time heart health monitoring</p>
    <div class="tabs" role="tablist">
      <button id="tab-login" type="button" role="tab" aria-selected="true">Login</button>
      <button id="tab-register" type="button" role="tab" aria-selected="false">Register</button>
    </div>
    <label id="name-field" class="field hidden"><span>Full name</span><input id="name" type="text" maxlength="100" autocomplete="name"></label>
    <label class="field"><span>Email</span><input id="email" type="email" required minlength="5" maxlength="100" autocomplete="username"></label>
    <label class="field"><span>Password</span><input id="password" type="password" required minlength="6" maxlength="100" autocomplete="current-password"></label>
    <div id="login-error" class="error" role="alert"></div>
    <button id="login-btn" class="btn-primary" type="submit">Sign In</button>
  </form>
</section>

<!-- ─────────────── Dashboard ─────────────── -->
<main id="app" class="wrap hidden">
  <header class="top">
    <div class="greet">
      <h1 id="greeting">Hello</h1>
      <div class="date" id="today"></div>
    </div>
    <div class="controls">
      <label class="pill" title="Device"><span>Device</span><select id="device"></select></label>
      <span class="pill" id="link" aria-live="polite"><span class="dot" id="link-dot"></span><span id="link-text">Connecting…</span></span>
      <button class="btn-ghost" id="logout" type="button">Log out</button>
    </div>
  </header>

  <div class="grid">
    <!-- Heart rate -->
    <div class="vital">
      <div class="top">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.8 4.6a5.5 5.5 0 0 0-7.8 0L12 5.7l-1-1.1a5.5 5.5 0 1 0-7.8 7.8L12 21l8.8-8.6a5.5 5.5 0 0 0 0-7.8z"/><path d="M3.5 12h4l1.5-3 3 6 1.5-3h7"/></svg>
        <span>Heart Rate</span><em class="status" id="hr-status"></em>
      </div>
      <div class="big" id="hr">--</div>
      <div class="unit" id="hr-unit">bpm</div>
      <div class="foot"><div class="bar"><i id="hr-bar"></i></div></div>
    </div>

    <!-- Risk assessment -->
    <div class="card span-2">
      <div class="card-head">
        <div class="icon-box" id="risk-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/><path d="M9 12l2 2 4-4"/></svg>
        </div>
        <h2>Risk Assessment<span class="sub">ECGFounder + XGBoost ensemble · abnormal-ECG screening</span></h2>
      </div>
      <div class="risk-row">
        <span class="risk-num" id="risk-num">--</span><span class="risk-pct" id="risk-pct"></span>
        <span class="risk-label" id="risk-label">N/A</span>
      </div>
      <div class="risk-bar"><i id="risk-dim" style="width:100%"></i></div>
      <div class="scale"><span>Low</span><span>High</span></div>
      <div class="meta" id="risk-meta"></div>
      <div class="notice hidden" id="risk-notice"></div>
    </div>

    <!-- ECG -->
    <div class="card span-3">
      <div class="card-head">
        <div class="icon-box" style="background:rgba(13,148,136,.12);color:#0D9488">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12h4l2-6 4 12 2-6h8"/></svg>
        </div>
        <h2>ECG Waveform<span class="sub" id="ecg-sub">Latest 10 s window</span></h2>
        <span class="chip hidden" id="quality-chip"></span>
        <span class="chip" id="ecg-badge"></span>
      </div>
      <div class="source hidden" id="source"></div>
      <div class="ecg-wrap">
        <canvas id="ecg"></canvas>
        <div class="overlay hidden" id="ecg-overlay"></div>
      </div>
    </div>

    <!-- Risk trend -->
    <div class="card span-2">
      <div class="card-head">
        <div class="icon-box" style="background:rgba(13,148,136,.12);color:#0D9488">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M7 15l4-4 3 3 5-6"/></svg>
        </div>
        <h2>Risk Trend<span class="sub">Last 30 assessments</span></h2>
      </div>
      <div class="trend-wrap"><canvas id="trend"></canvas></div>
    </div>

    <!-- Device status -->
    <div class="card">
      <div class="card-head"><h2 style="font-size:12px;letter-spacing:.5px;color:var(--text2)">DEVICE STATUS</h2></div>
      <div class="status-grid">
        <div class="stat" id="st-link"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5a10 10 0 0 1 14 0"/><path d="M8.5 16a5 5 0 0 1 7 0"/><path d="M12 19.5h.01"/></svg></div><div><b>Data link</b><span>–</span></div></div>
        <div class="stat" id="st-leads"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12h4l2-6 4 12 2-6h8"/></svg></div><div><b>Electrodes</b><span>–</span></div></div>
        <div class="stat" id="st-signal"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20V14"/><path d="M10 20V9"/><path d="M16 20V4"/></svg></div><div><b>Signal</b><span>–</span></div></div>
        <div class="stat" id="st-model"><div class="icon-box"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="5" width="14" height="14" rx="2"/><path d="M9 1v4M15 1v4M9 19v4M15 19v4M1 9h4M1 15h4M19 9h4M19 15h4"/></svg></div><div><b>Risk model</b><span>–</span></div></div>
      </div>
    </div>
  </div>

  <footer>
    Prototype screening tool — not a medical device. Devices marked <b>RECORDED</b> replay stored ECGs and are not live.<br>
    <span id="updated"></span>
  </footer>
</main>

<script>
(() => {
  "use strict";

  // Same-origin by default; ?api=https://… lets a local copy talk to a deployed API.
  const API = (new URLSearchParams(location.search).get("api") || "").replace(/\/$/, "");
  const POLL_MS = 5000;
  const LIVE_WINDOW_S = 40;            // a new window arrives every ~10 s; allow upload latency
  const TOKEN_KEY = "cm_dashboard_token";
  const DEVICE_KEY = "cm_dashboard_device";
  const REQUEST_TIMEOUT_MS = 20000;     // a hung request must never freeze the page
  const RISK = [[0.2, "normal", "#22C55E"], [0.4, "low", "#84CC16"], [0.6, "moderate", "#EAB308"],
                [0.8, "elevated", "#F97316"], [Infinity, "high", "#EF4444"]];

  const $ = (id) => document.getElementById(id);
  const store = {
    get(k) { try { return localStorage.getItem(k); } catch { return null; } },
    set(k, v) { try { localStorage.setItem(k, v); } catch { /* private mode */ } },
    del(k) { try { localStorage.removeItem(k); } catch { /* private mode */ } },
  };

  let token = store.get(TOKEN_KEY);
  let device = null;
  let pollTimer = null;
  let refreshSeq = 0;                  // only the newest refresh may update the screen
  let lastEcg = null, lastTrend = [];

  // ── helpers ──
  const utc = (s) => s ? new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : s + "Z") : null;  // API sends naive UTC
  const hms = (d) => d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
  const ago = (d) => {
    const s = Math.max(0, (Date.now() - d.getTime()) / 1000);
    if (s < 60) return `${Math.round(s)} s ago`;
    if (s < 3600) return `${Math.round(s / 60)} min ago`;
    if (s < 86400) return `${Math.round(s / 3600)} h ago`;
    return `${Math.round(s / 86400)} d ago`;
  };
  const riskColor = (score) => RISK.find(([max]) => score < max)[2];
  const isPlayback = (id) => id.startsWith("PLAYBACK_");
  const css = (name) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();

  async function timedFetch(url, opts = {}) {
    const ctrl = new AbortController();
    const timer = setTimeout(() => ctrl.abort(), REQUEST_TIMEOUT_MS);
    try { return await fetch(url, Object.assign({}, opts, { signal: ctrl.signal })); }
    catch (err) { throw new Error(err.name === "AbortError" ? "The server took too long to respond." : "Cannot reach the server."); }
    finally { clearTimeout(timer); }
  }

  async function api(path, opts = {}) {
    const headers = Object.assign({ "Content-Type": "application/json" }, opts.headers || {});
    if (token) headers.Authorization = `Bearer ${token}`;
    const res = await timedFetch(API + path, Object.assign({}, opts, { headers }));
    if (res.status === 401 && token) { logout("Your session expired. Please sign in again."); throw new Error("unauthorized"); }
    return res;
  }

  // ── auth ──
  function showLogin(message = "") {
    stopPolling();
    $("app").classList.add("hidden");
    $("login").classList.remove("hidden");
    $("login-error").textContent = message;
  }
  function logout(message = "") {
    token = null; store.del(TOKEN_KEY);
    showLogin(message);
  }

  // Login / Register toggle, as in the app's login screen
  let registering = false;
  function setMode(register) {
    registering = register;
    $("tab-login").setAttribute("aria-selected", String(!register));
    $("tab-register").setAttribute("aria-selected", String(register));
    $("name-field").classList.toggle("hidden", !register);
    $("name").required = register;
    $("password").autocomplete = register ? "new-password" : "current-password";
    $("login-btn").textContent = register ? "Create Account" : "Sign In";
    $("login-error").textContent = "";
  }
  $("tab-login").addEventListener("click", () => setMode(false));
  $("tab-register").addEventListener("click", () => setMode(true));

  $("login-form").addEventListener("submit", async (e) => {
    e.preventDefault();
    const btn = $("login-btn");
    btn.disabled = true; $("login-error").textContent = "";
    try {
      const creds = { email: $("email").value.trim(), password: $("password").value };
      if (registering) creds.name = $("name").value.trim();
      if (registering && !creds.name) throw new Error("Name required");
      const res = await timedFetch(API + (registering ? "/api/v1/auth/register" : "/api/v1/auth/login"), {
        method: "POST", headers: { "Content-Type": "application/json" },
        body: JSON.stringify(creds),
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok) {
        if (typeof body.detail === "string") throw new Error(body.detail);
        throw new Error(registering ? "Please check your name, email and password." : "Sign-in failed");
      }
      token = body.access_token; store.set(TOKEN_KEY, token);
      $("password").value = ""; $("name").value = "";
      setMode(false);
      await start();
    } catch (err) {
      $("login-error").textContent = err.message;
    } finally { btn.disabled = false; }
  });
  $("logout").addEventListener("click", () => logout());

  // ── startup ──
  async function start() {
    const res = await api("/api/v1/auth/me");
    if (!res.ok) { logout(); return; }
    const me = await res.json();
    $("greeting").textContent = `Hello, ${(me.name || "there").split(" ")[0]}`;
    $("today").textContent = new Date().toLocaleDateString([], { weekday: "long", month: "long", day: "numeric" });

    const sel = $("device");
    sel.textContent = "";
    const ids = me.device_ids || [];
    if (!ids.length) {
      sel.append(new Option("No devices", ""));
    }
    for (const id of ids) sel.append(new Option(isPlayback(id) ? `${id} (recorded)` : id, id));
    const saved = store.get(DEVICE_KEY);
    device = ids.includes(saved) ? saved : await pickDefaultDevice(ids);
    if (device) sel.value = device;

    $("login").classList.add("hidden");
    $("app").classList.remove("hidden");
    startPolling();
  }

  // Prefer the live device that uploaded most recently: an account can also list unused IDs
  // (e.g. a name typed into the app's "Device ID" field) that would open on an empty screen.
  async function pickDefaultDevice(ids) {
    const live = ids.filter((id) => !isPlayback(id));
    const latest = await Promise.all(live.map(async (id) => {
      try {
        const r = await api(`/api/v1/vitals/${encodeURIComponent(id)}/latest`);
        return [id, r.ok ? utc((await r.json()).created_at).getTime() : -1];
      } catch { return [id, -1]; }
    }));
    latest.sort((a, b) => b[1] - a[1]);
    return (latest.length && latest[0][1] >= 0 ? latest[0][0] : live[0]) || ids[0] || null;
  }

  $("device").addEventListener("change", (e) => {
    device = e.target.value; store.set(DEVICE_KEY, device);
    lastEcg = null; lastTrend = [];
    startPolling();
  });

  function startPolling() { stopPolling(); refresh(); pollTimer = setInterval(refresh, POLL_MS); }
  function stopPolling() { if (pollTimer) clearInterval(pollTimer); pollTimer = null; }
  document.addEventListener("visibilitychange", () => {
    if (!token || $("app").classList.contains("hidden")) return;
    document.hidden ? stopPolling() : startPolling();
  });

  // ── data refresh ──
  async function refresh() {
    if (!device) { renderEmpty("No device is linked to this account."); return; }
    const seq = ++refreshSeq, dev = device;
    const stale = () => seq !== refreshSeq || dev !== device;   // device switched or a newer refresh started
    try {
      const enc = encodeURIComponent(dev);
      const [vRes, pRes] = await Promise.all([
        api(`/api/v1/vitals/${enc}/latest?include_ecg=true`),
        api(`/api/v1/predictions/${enc}?limit=30`),
      ]);
      if (stale()) return;
      if (vRes.status === 403) { renderEmpty("This account has no access to this device."); return; }
      const vitals = vRes.status === 404 ? null : (vRes.ok ? await vRes.json() : undefined);
      const preds = pRes.ok ? (await pRes.json()).predictions || [] : [];
      if (vitals === undefined) throw new Error(`HTTP ${vRes.status}`);
      if (stale()) return;
      render(vitals, preds);
      $("updated").textContent = `Dashboard updated ${hms(new Date())}`;
    } catch (err) {
      if (err.message === "unauthorized" || stale()) return;
      setLink(false, "Server unreachable");
      $("updated").textContent = `Last refresh failed (${err.message}) — retrying…`;
    }
  }

  function setLink(live, text) {
    $("link-dot").classList.toggle("live", live);
    $("link-text").textContent = text;
  }

  function setStat(id, state, text) {
    const el = $(id);
    el.classList.remove("ok", "warn");
    if (state) el.classList.add(state);
    el.querySelector("span").textContent = text;
  }

  function renderEmpty(message) {
    setLink(false, "No data");
    showOverlay(message, "");
    lastEcg = null; drawEcg();
    renderRisk(null, null, null);
    renderHr(null);
    lastTrend = []; drawTrend();
  }

  function render(v, preds) {
    if (!v) { renderEmpty("No ECG received from this device yet."); renderTrend(preds); return; }
    const created = utc(v.created_at);
    const ageS = (Date.now() - created.getTime()) / 1000;
    const live = ageS <= LIVE_WINDOW_S && !isPlayback(v.device_id);
    const playback = isPlayback(v.device_id) || !!v.source;

    // header status
    setLink(live, playback ? "Recorded data" : live ? "Live" : `Offline · last data ${ago(created)}`);

    // ECG card
    const badge = $("ecg-badge");
    badge.className = "chip";
    if (playback) { badge.classList.add("playback-badge"); badge.textContent = "RECORDED · NOT LIVE"; }
    else if (live) { badge.classList.add("live-badge"); badge.innerHTML = '<span class="dot live" style="width:6px;height:6px"></span>LIVE'; }
    else { badge.textContent = hms(created); }
    $("source").classList.toggle("hidden", !v.source);
    $("source").textContent = v.source || "";
    const rate = v.sample_rate_hz || 250;
    $("ecg-sub").textContent = `${((v.ecg_samples || []).length / rate).toFixed(0)} s window · ${rate} Hz · ${hms(created)}`;

    const q = v.signal_quality;
    const qc = $("quality-chip");
    qc.classList.toggle("hidden", !q);
    qc.textContent = q === "good" ? "Signal good" : q === "poor" ? "Signal poor" : q === "lead_off" ? "Leads off" : "";
    qc.style.background = q === "good" ? "rgba(34,197,94,.12)" : "rgba(234,179,8,.14)";
    qc.style.color = q === "good" ? "var(--normal)" : "var(--moderate)";

    lastEcg = { samples: v.ecg_samples || [], rate, leadOff: v.ecg_lead_off };
    if (v.ecg_lead_off) showOverlay("Electrodes are off", "No ECG in the latest window — attach all three pads");
    else hideOverlay();
    drawEcg();

    // Heart rate
    renderHr(v.heart_rate_bpm > 0 ? v.heart_rate_bpm : null, v.heart_rate_source);

    // Risk: the latest window's own prediction, else the most recent stored one (clearly labelled)
    const latestPred = preds[0] || null;
    renderRisk(v, v.prediction, latestPred);
    renderTrend(preds);

    // Device status
    setStat("st-link", live ? "ok" : null, playback ? "Recorded session" : live ? "Uploading every 10 s" : `Last seen ${ago(created)}`);
    setStat("st-leads", v.ecg_lead_off ? "warn" : "ok", v.ecg_lead_off ? "Not attached" : "Attached");
    setStat("st-signal", q === "good" ? "ok" : q ? "warn" : null, q === "good" ? "Clean ECG" : q === "poor" ? "Too noisy to score" : q === "lead_off" ? "No signal" : "–");
    setStat("st-model", latestPred ? "ok" : null, latestPred ? `${preds.length} recent assessments` : "No assessments yet");
  }

  function renderHr(hr, source) {
    $("hr").textContent = hr ? Math.round(hr) : "--";
    $("hr-unit").textContent = hr ? (source === "ecg" ? "bpm · from ECG" : "bpm") : "bpm";
    $("hr-status").textContent = !hr ? "" : hr < 60 ? "Low" : hr > 100 ? "High" : "Normal";
    $("hr-status").classList.toggle("hidden", !hr);
    $("hr-bar").style.width = hr ? `${Math.min(100, Math.max(0, (hr - 40) / 120 * 100))}%` : "0";
  }

  function renderRisk(v, windowPred, latestPred) {
    const p = windowPred || latestPred;
    const num = $("risk-num"), label = $("risk-label"), icon = $("risk-icon");
    const notice = $("risk-notice");
    if (!p) {
      num.textContent = "--"; num.style.color = "var(--text3)"; $("risk-pct").textContent = "";
      label.textContent = "N/A"; label.style.background = "var(--surface)"; label.style.color = "var(--text2)";
      icon.style.background = "var(--surface)"; icon.style.color = "var(--text3)";
      $("risk-dim").style.width = "100%";
      $("risk-meta").textContent = "";
      notice.classList.toggle("hidden", !v);
      notice.textContent = v ? "No risk assessment yet — the model only scores clean ECG windows." : "";
      return;
    }
    const score = p.risk_score, color = riskColor(score);
    num.textContent = Math.round(score * 100); num.style.color = color; $("risk-pct").textContent = "%";
    $("risk-pct").style.color = color;
    label.textContent = p.risk_label; label.style.background = color + "1F"; label.style.color = color;
    icon.style.background = color + "1F"; icon.style.color = color;
    $("risk-dim").style.width = `${(1 - Math.min(1, Math.max(0, score))) * 100}%`;

    const when = p.created_at ? hms(utc(p.created_at)) : (v ? hms(utc(v.created_at)) : "");
    const meta = $("risk-meta");
    meta.textContent = "";
    for (const t of [`Confidence ${Math.round((p.confidence || 0) * 100)}%`, `Assessed ${when}`]) {
      const s = document.createElement("span"); s.textContent = t; meta.append(s);
    }
    if (!windowPred && v) {
      const why = v.ecg_lead_off ? "electrodes were off" : v.signal_quality === "poor" ? "the signal was too noisy" : "it has not been scored";
      notice.textContent = `The latest window was not scored because ${why}. Showing the last assessment from ${when}.`;
      notice.classList.remove("hidden");
    } else { notice.classList.add("hidden"); notice.textContent = ""; }
  }

  function renderTrend(preds) {
    lastTrend = preds.slice().reverse();     // oldest → newest
    drawTrend();
  }

  // ── canvas drawing ──
  function setupCanvas(canvas) {
    const dpr = window.devicePixelRatio || 1;
    const w = canvas.clientWidth, h = canvas.clientHeight;
    if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {
      canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr);
    }
    const ctx = canvas.getContext("2d");
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.clearRect(0, 0, w, h);
    return { ctx, w, h };
  }

  function showOverlay(title, detail) {
    const o = $("ecg-overlay");
    o.textContent = "";
    const t = document.createElement("div"); t.textContent = title;
    const d = document.createElement("small"); d.textContent = detail;
    t.append(d); o.append(t); o.classList.remove("hidden");
  }
  function hideOverlay() { $("ecg-overlay").classList.add("hidden"); }

  function drawEcg() {
    const { ctx, w, h } = setupCanvas($("ecg"));
    const padB = 20, plotH = h - padB;
    const data = lastEcg && !lastEcg.leadOff ? lastEcg.samples : [];
    const secs = lastEcg ? Math.max(1, Math.round(lastEcg.samples.length / lastEcg.rate)) : 10;

    // grid: one vertical line per second (ECG paper style), 4 horizontal lines
    ctx.strokeStyle = css("--grid"); ctx.lineWidth = 1;
    ctx.beginPath();
    for (let s = 0; s <= secs; s++) { const x = Math.round((s / secs) * (w - 1)) + 0.5; ctx.moveTo(x, 0); ctx.lineTo(x, plotH); }
    for (let i = 0; i <= 4; i++) { const y = Math.round((i / 4) * (plotH - 1)) + 0.5; ctx.moveTo(0, y); ctx.lineTo(w, y); }
    ctx.stroke();
    ctx.fillStyle = css("--text3"); ctx.font = "500 10px 'Plus Jakarta Sans', sans-serif";
    ctx.textBaseline = "bottom";
    for (let s = 0; s <= secs; s += 2) {
      const x = (s / secs) * (w - 1);
      ctx.textAlign = s === 0 ? "left" : s === secs ? "right" : "center";
      ctx.fillText(`${s}s`, x, h - 2);
    }
    if (!data.length) return;

    // y range with padding
    let lo = Infinity, hi = -Infinity;
    for (const v of data) { if (v < lo) lo = v; if (v > hi) hi = v; }
    const pad = Math.max(20, (hi - lo) * 0.1); lo -= pad; hi += pad;
    const y = (v) => plotH - ((v - lo) / (hi - lo)) * plotH;

    // peak-preserving draw: min and max of each pixel column, in time order
    const n = data.length, cols = Math.max(1, Math.floor(w));
    const accent = css("--accent");
    ctx.beginPath();
    for (let c = 0; c < cols; c++) {
      const a = Math.floor((c / cols) * n), b = Math.max(a + 1, Math.floor(((c + 1) / cols) * n));
      let mi = a, ma = a;
      for (let i = a; i < b && i < n; i++) { if (data[i] < data[mi]) mi = i; if (data[i] > data[ma]) ma = i; }
      const first = Math.min(mi, ma), second = Math.max(mi, ma);
      const x = (c / (cols - 1 || 1)) * (w - 1);
      if (c === 0) ctx.moveTo(x, y(data[first])); else ctx.lineTo(x, y(data[first]));
      if (second !== first) ctx.lineTo(x, y(data[second]));
    }
    ctx.strokeStyle = accent; ctx.lineWidth = 1.4; ctx.lineJoin = "round"; ctx.stroke();
  }

  function drawTrend() {
    const { ctx, w, h } = setupCanvas($("trend"));
    const padL = 40, padB = 18, padT = 6, plotW = w - padL - 6, plotH = h - padB - padT;
    // risk bands
    let prev = 0;
    for (const [max, , color] of RISK) {
      const top = Math.min(1, max);
      ctx.fillStyle = color + "14";
      ctx.fillRect(padL, padT + plotH * (1 - top), plotW, plotH * (top - prev));
      prev = top;
    }
    ctx.fillStyle = css("--text3"); ctx.font = "500 10px 'Plus Jakarta Sans', sans-serif";
    ctx.textAlign = "right"; ctx.textBaseline = "middle";
    for (const v of [0, 0.5, 1]) ctx.fillText(`${v * 100}%`, padL - 6, padT + plotH * (1 - v));
    if (!lastTrend.length) {
      ctx.textAlign = "center"; ctx.fillText("No assessments yet", padL + plotW / 2, padT + plotH / 2);
      return;
    }
    const pts = lastTrend.map((p, i) => [
      padL + (lastTrend.length === 1 ? plotW / 2 : (i / (lastTrend.length - 1)) * plotW),
      padT + plotH * (1 - p.risk_score), p.risk_score]);
    ctx.beginPath();
    pts.forEach(([x, yy], i) => (i ? ctx.lineTo(x, yy) : ctx.moveTo(x, yy)));
    ctx.strokeStyle = css("--accent"); ctx.lineWidth = 1.5; ctx.stroke();
    for (const [x, yy, s] of pts) {
      ctx.beginPath(); ctx.arc(x, yy, 3.2, 0, Math.PI * 2);
      ctx.fillStyle = riskColor(s); ctx.fill();
    }
    ctx.textBaseline = "bottom"; ctx.fillStyle = css("--text3");
    ctx.textAlign = "left"; ctx.fillText(hms(utc(lastTrend[0].created_at)), padL, h);
    ctx.textAlign = "right"; ctx.fillText(hms(utc(lastTrend[lastTrend.length - 1].created_at)), padL + plotW, h);
  }

  let resizeT;
  window.addEventListener("resize", () => { clearTimeout(resizeT); resizeT = setTimeout(() => { drawEcg(); drawTrend(); }, 100); });
  window.matchMedia("(prefers-color-scheme: dark)").addEventListener?.("change", () => { drawEcg(); drawTrend(); });

  // ── go ──
  // A 401 inside start() has already logged out with a message; only fall back for other errors
  if (token) start().catch(() => { if (token) showLogin("Cannot reach the server. Please try again."); });
  else showLogin();
})();
</script>
</body>
</html>