File size: 32,394 Bytes
07b78d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29693f8
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>SUD Interactive Suite — v5.3 (Shuffle + Named PDF)</title>
  <style>
    :root{ --bg:#ffffff; --fg:#101114; --muted:#61656f; --border:#e6e7eb; --card:#f8f9fb;
           --accent:#2563eb; --dep:#2e7d32; --tol:#6a1b9a; --dsm:#ef6c00; --wd:#0b6b6b;
           --branch:#1f2937; }
    *{ box-sizing:border-box; } html,body{ height:100%; }
    body{ margin:0; background:var(--bg); color:var(--fg);
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial;
      line-height:1.45; }
    h1{ font-size:1.6rem; margin:0 0 .25rem 0; } h2{ font-size:1.2rem; margin:.4rem 0; } h3{ font-size:1.05rem; margin:.4rem 0; }
    p, li, label, button, input, select, textarea{ font-size:1rem; } .small{ font-size:.92rem; } .muted{ color:var(--muted); }
    .pill{ display:inline-block; padding:4px 10px; border:1px solid var(--border); border-radius:999px; background:#eef2ff; color:#223b94; font-size:.9rem; }
    .tag{ display:inline-block; padding:2px 6px; border:1px solid var(--border); border-radius:999px; font-size:.78rem; margin:0 6px 6px 0; background:#fff; }
    .hr{ height:1px; background:var(--border); margin:12px 0; } .hidden{ display:none !important; }
    header{ padding:18px; border-bottom:1px solid var(--border); background:linear-gradient(180deg, #f3f6ff, #ffffff); }
    main{ max-width:860px; margin:0 auto; padding:16px; }
    .card{ background:var(--card); border:1px solid var(--border); border-radius:16px; padding:16px; }
    input[type="text"], select, textarea{ padding:10px 12px; border-radius:10px; border:1px solid var(--border); background:#fff; width:100%; }
    button{ padding:10px 12px; border-radius:10px; border:1px solid var(--border); background:#fff; cursor:pointer; font-weight:600; }
    button.primary{ background:var(--accent); color:#fff; border-color:var(--accent); }
    .choices button{ width:100%; text-align:left; margin:6px 0; }
    .sectionTitle{ display:flex; align-items:center; gap:8px; margin:8px 0 6px 0; }
    .dot{ width:10px; height:10px; border-radius:999px; }
    .dep .sectionTitle .dot{ background:var(--dep); } .tol .sectionTitle .dot{ background:var(--tol); }
    .dsm .sectionTitle .dot{ background:var(--dsm); } .wd  .sectionTitle .dot{ background:var(--wd); }
    .dep{ border-left:4px solid var(--dep); padding-left:10px; } .tol{ border-left:4px solid var(--tol); padding-left:10px; }
    .dsm{ border-left:4px solid var(--dsm); padding-left:10px; } .wd{  border-left:4px solid var(--wd);  padding-left:10px; }
    .branchHeader{ margin:8px 0 6px 0; color:#fff; background:var(--branch); padding:8px 10px; border-radius:10px; font-weight:700; }
    .list{ margin:.4rem 0 .2rem 1.2rem; }
    /* Modal */
    .modal{ position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; padding:20px; z-index:1000; }
    .modal.hidden{ display:none; }
    .modalBox{ background:#fff; border-radius:14px; border:1px solid var(--border); max-width:760px; width:100%; padding:16px; box-shadow: 0 10px 40px rgba(0,0,0,.1); }
    .modalBox h3{ margin-top:0; }
    .modalBody{ color:#111; }
    .modalBody ul{ margin:.4rem 0 .2rem 1.2rem; }
    .modalActions{ display:flex; justify-content:flex-end; gap:8px; margin-top:10px; }
    .ok{ background:var(--accent); color:#fff; border-color:var(--accent); }
    /* Lock overlay after final */
    #lockOverlay{ position:fixed; inset:0; background:rgba(255,255,255,.95); z-index:2000; display:none; align-items:center; justify-content:center; padding:24px; text-align:center; }
    #lockOverlay .box{ max-width:720px; border:1px solid var(--border); background:#fff; border-radius:16px; padding:24px; }
    #lockOverlay h2{ margin-top:0; }
    @media print{ .modal, #lockOverlay{ display:none !important; } header { display:none !important; } body{ background:#fff; } .card{ border:none; } }
  </style>
</head>
<body>
  <header>
    <h1>SUD Interactive Suite — v5.3</h1>
    <p class="muted">Work through three branching cases (Cannabis → Alcohol → Opioid). First scene asks about tolerance; later scenes ask you to distinguish psychological vs physiological dependence and classify DSM-5 criteria. A taper scene includes a withdrawal checklist. Final screen: choose the overall SUD severity.</p>
    <div class="card" style="display:flex; gap:12px; align-items:center; flex-wrap:wrap;">
      <span class="pill">Student name (required)</span>
      <input id="studentName" type="text" placeholder="Type your name to begin"/>
      <button id="resetBtn" type="button" class="ok" style="background:#fff;color:#111;border-color:var(--border)">Reset</button>
    </div>
  </header>

  <main>
    <section class="card" aria-live="polite">
      <h2 id="sceneTitle">Scene</h2>
      <div id="sceneText" class="small"></div>
      <div id="tagRow" class="small"></div>

      <div id="promptTolerance" class="tol hidden">
        <div class="sectionTitle"><span class="dot"></span><h3>Tolerance check</h3></div>
        <p class="small">Does this scene show tolerance (needing more for same effect, or diminished effect at same amount)?</p>
        <div>
          <button class="primary" type="button" id="btnTolYes">Yes — tolerance is present</button>
          <button class="primary" type="button" id="btnTolNo">No — not tolerance</button>
        </div>
        <p id="tolStatus" class="small muted"></p>
      </div>

      <div id="promptDependence" class="dep hidden">
        <div class="sectionTitle"><span class="dot"></span><h3>Dependence: psychological or physiological?</h3></div>
        <p class="small">Symptoms in this scene:</p>
        <ul id="symptomList" class="list small"></ul>
        <div>
          <button class="primary" type="button" id="btnPsych">Psychological dependence</button>
          <button class="primary" type="button" id="btnPhys">Physiological dependence</button>
        </div>
        <p id="depStatus" class="small muted"></p>
      </div>

      <div id="promptDSM" class="dsm hidden">
        <div class="sectionTitle"><span class="dot"></span><h3>Classify DSM-5 criteria in this scene</h3></div>
        <div id="dsmRows"></div>
      </div>

      <div id="promptWD" class="wd hidden">
        <div class="sectionTitle"><span class="dot"></span><h3>Tapering: Withdrawal checklist</h3></div>
        <p class="small">While using, the case experienced: <span id="wdEffects" class="badge"></span></p>
        <p class="small">Select the likely withdrawal symptoms (choose all that apply):</p>
        <div id="wdOptions"></div>
        <p id="wdStatus" class="small muted"></p>
      </div>

      <div id="branchHeader" class="branchHeader hidden">Choose what happens next…</div>
      <div id="choices" class="choices"></div>
      <p id="feedback" class="muted"></p>

      <!-- Final page content -->
      <div id="finalBlock" class="card hidden" style="margin-top:12px;">
        <div class="sectionTitle"><span class="dot" style="background:var(--dsm)"></span><h3>Final: Overall SUD severity</h3></div>
        <div id="finalSummary" class="small"></div>
        <p style="margin:.5rem 0 .25rem 0;"><b>Choose one:</b></p>
        <div class="checkRow"><input type="radio" name="sev" id="sev0" value="None"><label for="sev0">No SUD</label></div>
        <div class="checkRow"><input type="radio" name="sev" id="sev1" value="Mild"><label for="sev1">Mild SUD</label></div>
        <div class="checkRow"><input type="radio" name="sev" id="sev2" value="Moderate"><label for="sev2">Moderate SUD</label></div>
        <div class="checkRow"><input type="radio" name="sev" id="sev3" value="Severe"><label for="sev3">Severe SUD</label></div>
        <div style="margin-top:14px;"><button id="submitCaseBtn" type="button" class="primary">Submit Case</button></div>
      </div>
    </section>
  </main>

  <!-- Modal -->
  <div id="modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
    <div class="modalBox">
      <h3 id="modalTitle">Notice</h3>
      <div id="modalBody" class="modalBody"></div>
      <div class="modalActions">
        <button id="modalOk" type="button" class="ok">OK</button>
      </div>
    </div>
  </div>

  <!-- Lock overlay after final completion -->
  <div id="lockOverlay">
    <div class="box">
      <h2>You're done! 🎉</h2>
      <p class="small">Your proof of completion has been downloaded as a PDF. Upload it to Canvas for participation credit.</p>
      <p class="small">If you need to redo the activity, close this tab and re-open the assignment link.</p>
    </div>
  </div>

  <script>
  (function(){
    document.addEventListener("DOMContentLoaded", function(){

      const DSM5 = [
        {text:"1. Larger amounts/longer than intended", domain:"impaired"},
        {text:"2. Persistent desire/unsuccessful efforts to cut down", domain:"impaired"},
        {text:"3. Much time spent obtaining/using/recovering", domain:"impaired"},
        {text:"4. Craving or strong urge to use", domain:"impaired"},
        {text:"5. Recurrent use causing role failures", domain:"social"},
        {text:"6. Continued use despite social/interpersonal problems", domain:"social"},
        {text:"7. Activities given up or reduced", domain:"social"},
        {text:"8. Recurrent use in hazardous situations", domain:"risky"},
        {text:"9. Continued use despite physical/psych problems", domain:"risky"},
        {text:"10. Tolerance", domain:"pharm"},
        {text:"11. Withdrawal", domain:"pharm"}
      ];
      const labelDomain = (d) => d==="impaired" ? "Impaired control" : d==="social" ? "Social impairment" : d==="risky" ? "Risky use" : "Pharmacological";
      const T = (...tags) => tags;
      const isEndKey = key => typeof key === "string" && key.endsWith("end");
      const rngShuffle = (arr) => arr.map((v,i)=>({v, i, r:Math.random()})).sort((a,b)=>a.r-b.r).map(o=>o);

      let LOCKED = false;

      const CASES = {
        cannabis: { label:"Alex — Cannabis", scenes:{
          c1:{ text:"Alex uses cannabis in the evening to relax after class. Initially, a small amount brings relaxation and sleep.",
               tags:T("evening use","relaxation","sleepiness"),
               choices:[{label:"After midterms approach, the same amount feels less relaxing",go:"c1tol",feedback:"Tolerance question."},
                        {label:"Keeps use the same; days feel stressful without it",go:"c2psych",feedback:"Psychological cues."}]},
          c1tol:{ text:"Over time, the same amount feels less relaxing than before; Alex considers increasing dose.",
               tags:T("diminished effect","considering more"), tol:true, dsm:[1],
               choices:[{label:"Increase dose and start earlier",go:"c3psych",feedback:"Impaired control likely."},
                        {label:"Try to cut down and set limits",go:"c2phys",feedback:"Observe symptoms while cutting down."}]},
          c2psych:{ text:"On days without cannabis, Alex feels tense, irritable, and preoccupied with planning the next session.",
               tags:T("irritability","preoccupation"), depExpected:"Psychological", dsm:[4],
               choices:[{label:"Use cannabis to relieve the tension",go:"c3social",feedback:"Watch for social impairment."},
                        {label:"Delay use and cope with supports",go:"c2phys",feedback:"Observe symptoms while cutting down."}]},
          c2phys:{ text:"After cutting down for 48 hours, Alex has decreased appetite, night sweats, and restlessness.",
               tags:T("↓ appetite","sweating","restlessness"), depExpected:"Physiological", dsm:[11],
               choices:[{label:"Resume evening use to feel normal",go:"c3psych",feedback:"Impaired control signals."},
                        {label:"Persist with supports",go:"c3social",feedback:"Social context next."}]},
          c3psych:{ text:"Alex experiences intrusive thoughts about using during the day and finds it hard to focus until planning the next session.",
               tags:T("craving","preoccupation"), depExpected:"Psychological", dsm:[4],
               choices:[{label:"Skip class after a late night using",go:"c3social",feedback:"Role/relationship effects."},
                        {label:"Begin tapering over the next week",go:"c4taper",feedback:"Withdrawal checklist."}]},
          c3social:{ text:"Late-night use leads to missed morning classes and arguments with roommates about reliability.",
               tags:T("missed classes","interpersonal conflict"), depExpected:"Psychological", dsm:[6,5],
               choices:[{label:"Continue despite problems",go:"c4taper",feedback:"Consider withdrawal when tapering."}]},
          c4taper:{ text:"Alex begins a taper. While using, effects included relaxation, increased appetite, and help falling asleep.",
               tags:T("tapering"), wd:{effects:["relaxation","increased appetite","sleep help"],
               options:[
                 {label:"Anxiety/irritability", correct:true},
                 {label:"Decreased appetite", correct:true},
                 {label:"Insomnia", correct:true},
                 {label:"Diarrhea", correct:false},
                 {label:"Piloerection (gooseflesh)", correct:false}
               ]}, dsm:[3,9],
               choices:[{label:"Finish",go:"c_end",feedback:"Go to final severity."}]},
          c_end:{ text:"Final page: choose overall SUD severity.", tags:T("wrap-up"), choices:[]}
        }},

        alcohol: { label:"Bri — Alcohol", scenes:{
          a1:{ text:"Bri drinks with friends on weekends. Over months, more drinks are needed to feel the same buzz.",
               tags:T("weekend use","more drinks"), tol:true, dsm:[10],
               choices:[{label:"Add weeknight drinks to relax",go:"a2psych",feedback:"Psych cues."},
                        {label:"Attempt to cut down",go:"a2phys",feedback:"Phys cues during cut-down."}]},
          a2psych:{ text:"On planned no-alcohol days, Bri feels anxious, irritable, and keeps thinking about having a drink to sleep.",
               tags:T("anxiety","irritability","preoccupation"), depExpected:"Psychological", dsm:[4],
               choices:[{label:"Have a nightcap to sleep",go:"a3social",feedback:"Role/relationship effects."},
                        {label:"Begin a taper with support",go:"a4taper",feedback:"Withdrawal checklist."}]},
          a2phys:{ text:"After a heavy weekend, two days off bring hand tremor and sweating.",
               tags:T("tremor","sweating"), depExpected:"Physiological", dsm:[11],
               choices:[{label:"Morning 'hair of the dog' to steady nerves",go:"a3social",feedback:"Likely risky/continued use."},
                        {label:"Taper this week",go:"a4taper",feedback:"Withdrawal checklist."}]},
          a3social:{ text:"Late nights lead to missed shifts/classes and arguments with friends about drinking.",
               tags:T("role failure","social conflict"), depExpected:"Psychological", dsm:[5,6],
               choices:[{label:"Begin tapering with a plan",go:"a4taper",feedback:"Withdrawal checklist."}]},
          a4taper:{ text:"Bri starts tapering. While using, effects included relaxation (anxiolysis), help falling asleep, and poor coordination.",
               tags:T("tapering"), wd:{effects:["anxiolysis","sleep help","impaired coordination"],
               options:[
                 {label:"Anxiety/restlessness", correct:true},
                 {label:"Insomnia", correct:true},
                 {label:"Tremor", correct:true},
                 {label:"Pinpoint pupils", correct:false},
                 {label:"Increased appetite", correct:false}
               ]}, dsm:[2,9],
               choices:[{label:"Finish",go:"a_end",feedback:"Go to final severity."}]},
          a_end:{ text:"Final page: choose overall SUD severity.", tags:T("wrap-up"), choices:[]}
        }},

        opioid: { label:"Cam — Opioid", scenes:{
          o1:{ text:"Cam is prescribed opioids for an injury. After a while, the same dose feels less euphoric.",
               tags:T("post-injury","diminished euphoria"), tol:true, dsm:[10],
               choices:[{label:"Takes doses earlier/bigger than prescribed",go:"o2psych",feedback:"Impaired control/psych cues."},
                        {label:"Attempts to cut down",go:"o2phys",feedback:"Phys cues during cut-down."}]},
          o2psych:{ text:"When trying to wait between doses, Cam becomes anxious, dysphoric, and preoccupied with the next dose.",
               tags:T("anxiety","dysphoria","preoccupation"), depExpected:"Psychological", dsm:[4],
               choices:[{label:"Seek non-prescribed pills",go:"o3risky",feedback:"Hazardous/continued use."},
                        {label:"Begin a supervised taper",go:"o4taper",feedback:"Withdrawal checklist."}]},
          o2phys:{ text:"When pills run out early, Cam has dilated pupils, muscle aches, and diarrhea.",
               tags:T("dilated pupils","aches","diarrhea"), depExpected:"Physiological", dsm:[11],
               choices:[{label:"Seek non-prescribed pills",go:"o3risky",feedback:"Hazardous/continued use."},
                        {label:"Begin a supervised taper",go:"o4taper",feedback:"Withdrawal checklist."}]},
          o3risky:{ text:"Cam continues use despite partner conflicts and drives while sedated to get pills.",
               tags:T("continued despite problems","hazardous driving"), depExpected:"Psychological", dsm:[6,8,9],
               choices:[{label:"Start taper and supports",go:"o4taper",feedback:"Withdrawal checklist."}]},
          o4taper:{ text:"Cam starts tapering. While using, effects included euphoria, miosis (pinpoint pupils), and constipation.",
               tags:T("tapering"), wd:{effects:["euphoria","miosis (pinpoint pupils)","constipation"],
               options:[
                 {label:"Low mood/anxiety", correct:true},
                 {label:"Dilated pupils", correct:true},
                 {label:"Diarrhea", correct:true},
                 {label:"Tremor", correct:false},
                 {label:"Nystagmus", correct:false}
               ]}, dsm:[2,9],
               choices:[{label:"Finish",go:"o_end",feedback:"Go to final severity."}]},
          o_end:{ text:"Final page: choose overall SUD severity.", tags:T("wrap-up"), choices:[]}
        }}
      };

      // ----- STATE -----
      const state = {
        caseKey:"cannabis", sceneKey:"c1",
        tolFlags:{}, depLabels:{},
        sceneDSM:{}, sceneWD:{},
        history:[], finalSeverity:null
      };

      const $ = id => document.getElementById(id);
      const hide = (el, yes) => { if(el) el.classList.toggle("hidden", yes); };
      const studentName = () => ($("studentName").value || "").trim();

      function firstSceneKey(){ const scenes = CASES[state.caseKey].scenes; return Object.keys(scenes)[0]; }
      function getNextCaseKey(){ const order = ["cannabis","alcohol","opioid"]; const i = order.indexOf(state.caseKey); return order[Math.min(i+1, order.length-1)]; }

      function setCase(key){
        if (LOCKED) return;
        state.caseKey = key;
        state.sceneKey = firstSceneKey();
        state.tolFlags = {}; state.depLabels = {}; state.sceneDSM = {}; state.sceneWD = {};
        state.history = []; state.finalSeverity = null;
        setScene(state.sceneKey);
      }

      function setScene(key, feedback=""){
        if (LOCKED) return;
        const pack = CASES[state.caseKey]; const sc = pack.scenes[key]; if(!sc) return;
        state.sceneKey = key;
        $("sceneTitle").textContent = `Scene — ${pack.label}`;
        $("sceneText").textContent = sc.text;
        $("feedback").textContent = feedback || "";
        $("tagRow").innerHTML = (sc.tags || []).map(t => `<span class="tag">${t}</span>`).join("");

        hide($("promptTolerance"), !sc.tol);
        if (sc.tol){
          $("tolStatus").textContent = (key in state.tolFlags) ? (state.tolFlags[key] ? "Recorded: tolerance present" : "Recorded: not tolerance") : "";
          $("btnTolYes").onclick = ()=>{ if(!studentName()) return needName(); state.tolFlags[key] = true; $("tolStatus").textContent = "Recorded: tolerance present"; };
          $("btnTolNo").onclick  = ()=>{ if(!studentName()) return needName(); state.tolFlags[key] = false; $("tolStatus").textContent = "Recorded: not tolerance"; };
        }

        hide($("promptDependence"), !sc.depExpected);
        if (sc.depExpected){
          const symptoms = (sc.tags || []).filter(t => !/wrap|tapering/i.test(t));
          $("symptomList").innerHTML = symptoms.map(s=>`<li>${s}</li>`).join("");
          $("depStatus").textContent = state.depLabels[key] ? `Recorded: ${state.depLabels[key]} dependence` : "";
          $("btnPsych").onclick = ()=>{ if(!studentName()) return needName(); state.depLabels[key] = "Psychological"; $("depStatus").textContent = "Recorded: Psychological dependence"; };
          $("btnPhys").onclick  = ()=>{ if(!studentName()) return needName(); state.depLabels[key] = "Physiological"; $("depStatus").textContent = "Recorded: Physiological dependence"; };
        }

        const dsmDiv = $("dsmRows"); dsmDiv.innerHTML = "";
        const haveDSM = Array.isArray(sc.dsm) && sc.dsm.length>0;
        hide($("promptDSM"), !haveDSM);
        if (haveDSM){
          state.sceneDSM[key] = state.sceneDSM[key] || {};
          sc.dsm.forEach(critIdx => {
            const row = document.createElement("div");
            row.className = "card"; row.style.margin="8px 0"; row.style.background="#fff";
            row.innerHTML = `
              <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                <div><b>${DSM5[critIdx-1].text}</b></div>
                <div>
                  <label class="small">Select domain</label>
                  <select data-crit="${critIdx}">
                    <option value="">— Choose —</option>
                    <option value="impaired">Impaired control</option>
                    <option value="social">Social impairment</option>
                    <option value="risky">Risky use</option>
                    <option value="pharm">Pharmacological</option>
                  </select>
                </div>
              </div>`;
            dsmDiv.appendChild(row);
            const sel = row.querySelector("select");
            sel.value = state.sceneDSM[key][critIdx] || "";
            sel.addEventListener("change", ()=>{ if(!studentName()) return needName(true); state.sceneDSM[key][critIdx] = sel.value; });
          });
        }

        hide($("promptWD"), !sc.wd);
        if (sc.wd){
          $("wdEffects").textContent = sc.wd.effects.join(", ");
          const wrap = $("wdOptions"); wrap.innerHTML = "";
          state.sceneWD[key] = state.sceneWD[key] || new Set();

          // SHUFFLE: render options in random order, track ORIGINAL index in data-idx
          const shuffled = rngShuffle(sc.wd.options);
          shuffled.forEach((optObj, displayIdx)=>{
            const opt = optObj.v, origIdx = optObj.i;
            const row = document.createElement("div"); row.className="checkRow";
            const id = `wd_${key}_${displayIdx}`;
            row.innerHTML = `<input type="checkbox" id="${id}" data-idx="${origIdx}"><label for="${id}">${opt.label}</label>`;
            wrap.appendChild(row);
            const cb = row.querySelector("input");
            cb.checked = state.sceneWD[key].has(origIdx);
            cb.addEventListener("change", ()=>{
              if(!studentName()) { cb.checked = false; return needName(true); }
              if (cb.checked) state.sceneWD[key].add(origIdx); else state.sceneWD[key].delete(origIdx);
            });
          });
          $("wdStatus").textContent = "";
        }

        const chDiv = $("choices"); chDiv.innerHTML = "";
        const hasChoices = (sc.choices || []).length > 0;
        hide($("branchHeader"), !hasChoices);
        $("branchHeader").textContent = `Choose what ${pack.label.split(' — ')[0]} will do next…`;
        (sc.choices || []).forEach(ch => {
          const b = document.createElement("button"); b.textContent = ch.label; b.type = "button";
          b.addEventListener("click", () => {
            if(!studentName()) return needName();
            const review = evaluateScene(key);
            if (review.ok){
              showModal("Great job!", "<p>Everything on this page looks accurate. Proceeding to the next scene.</p>", ()=>{
                state.history.push({ scene:key, choice:ch.label, ok:true });
                setScene(ch.go, ch.feedback || "");
              });
            } else {
              const list = review.issues.map(i=>`<li><b>${i.section}:</b> ${i.msg}</li>`).join("");
              showModal("Let's review…", `<p>Please revise before continuing:</p><ul>${list}</ul>`, ()=>{});
            }
          });
          chDiv.appendChild(b);
        });

        const isEnd = isEndKey(key);
        hide($("finalBlock"), !isEnd);
        if (isEnd){ renderFinal(); }
      }

      function needName(focus=false){
        showModal("Enter your name", "<p>Please type your name in the box at the top to continue.</p>", ()=>{ if (focus) $("studentName").focus(); });
      }

      function evaluateScene(sceneKey){
        const sc = CASES[state.caseKey].scenes[sceneKey];
        const issues = [];
        if (sc.tol){
          if (!(sceneKey in state.tolFlags)){ issues.push({section:"Tolerance", msg:"Decide whether tolerance is present on this first scene."}); }
        }
        if (sc.depExpected){
          const ans = state.depLabels[sceneKey];
          if (!ans){ issues.push({section:"Dependence", msg:"Classify the dependence as psychological vs physiological based on the symptoms."}); }
          else if (ans !== sc.depExpected){
            const hint = sc.depExpected==="Psychological" ? "Psychological = craving, preoccupation, anxiety, irritability, insomnia." : "Physiological = autonomic/bodily signs (e.g., tremor, sweating, GI changes, pupil changes).";
            issues.push({section:"Dependence", msg:hint});
          }
        }
        if (Array.isArray(sc.dsm) && sc.dsm.length>0){
          const m = state.sceneDSM[sceneKey] || {};
          sc.dsm.forEach(critIdx => {
            const want = DSM5[critIdx-1].domain;
            const have = m[critIdx] || "";
            if (!have) issues.push({section:"DSM-5", msg:`Choose a domain for “${DSM5[critIdx-1].text}”.`});
            else if (have !== want) issues.push({section:"DSM-5", msg:`Recheck the criterion wording and your domain classification.`});
          });
        }
        if (sc.wd){
          const sel = state.sceneWD[sceneKey] || new Set();
          const correctIdx = sc.wd.options.map((o,i)=>o.correct ? i : -1).filter(i=>i>=0);
          const selected = Array.from(sel).sort((a,b)=>a-b).join(",");
          const needed = correctIdx.sort((a,b)=>a-b).join(",");
          if (selected !== needed){
            issues.push({section:"Withdrawal", msg:"Select the likely withdrawal symptoms for this substance; avoid unrelated options."});
          }
        }
        return { ok: issues.length===0, issues };
      }

      function criteriaFromPath(){
        const visited = Array.from(new Set(state.history.map(h=>h.scene)));
        const list = [];
        visited.forEach(k => {
          const sc = CASES[state.caseKey].scenes[k];
          if (Array.isArray(sc.dsm)) sc.dsm.forEach(ci => list.push(ci));
        });
        return Array.from(new Set(list)).sort((a,b)=>a-b);
      }

      function renderFinal(){
        const pack = CASES[state.caseKey];
        const rows = state.history.map(h => `<tr><td>${h.scene}</td><td>${h.choice}</td></tr>`).join("");
        const critIdxs = criteriaFromPath();
        const items = critIdxs.map(i => `<li>${DSM5[i-1].text} — <em>${labelDomain(DSM5[i-1].domain)}</em></li>`).join("");
        $("finalSummary").innerHTML = `
          <p><b>Case:</b> ${pack.label}</p>
          <p><b>Your path:</b></p>
          <table style="width:100%;border-collapse:collapse" class="small">
            <thead><tr><th style="border:1px solid #ddd;padding:4px 6px;">Scene</th><th style="border:1px solid #ddd;padding:4px 6px;">Choice</th></tr></thead>
            <tbody>${rows}</tbody>
          </table>
          <p style="margin-top:.5rem;"><b>Criteria encountered on this path:</b></p>
          <ul>${items || "<li>(none)</li>"}</ul>`;
        $("submitCaseBtn").onclick = onSubmitCase;
      }

      function onSubmitCase(){
        if (!studentName()) return needName(true);
        const radios = document.querySelectorAll('input[name="sev"]');
        let chosen = null; radios.forEach(r => { if (r.checked) chosen = r.value; });
        if (!chosen){
          showModal("Let's review…", "<p>Please select an overall SUD severity.</p>", ()=>{});
          return;
        }
        state.finalSeverity = chosen;
        const next = getNextCaseKey();
        if (state.caseKey !== "opioid"){
          showModal("Great job!", `<p>Recorded severity: <b>${chosen}</b>.</p><p>Click OK to move to the next case: <b>${CASES[next].label}</b>.</p>`, ()=> setCase(next));
        } else {
          downloadProof();
          lockApp();
        }
      }

      // --- Minimal dynamic PDF generator (single line with name + date) ---
      function pdfEscape(s){ return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)"); }
      function makeProofPDF(text){
        const enc = (s)=> new TextEncoder().encode(s);
        const parts = [];
        let pos = 0;
        const offsets = [0];
        function add(s){ parts.push(s); pos += enc(s).length; }
        function obj(n, body){ offsets[n] = pos; add(`${n} 0 obj ${body} endobj\n`); }

        add('%PDF-1.4\n');
        obj(1, '<</Type /Catalog /Pages 2 0 R>>\n');
        obj(2, '<</Type /Pages /Count 1 /Kids [3 0 R]>>\n');
        obj(3, '<</Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources <</Font <</F1 5 0 R>>>>>>\n');

        const content = `BT /F1 24 Tf 72 720 Td (${pdfEscape(text)}) Tj ET\n`;
        obj(4, `<</Length ${enc(content).length}>> stream\n${content}endstream\n`);
        obj(5, '<</Type /Font /Subtype /Type1 /BaseFont /Helvetica>>\n');

        const xrefPos = pos;
        function pad(n){ return String(n).padStart(10,'0'); }
        let xref = 'xref\n0 6\n';
        xref += '0000000000 65535 f \n';
        for(let i=1;i<=5;i++) xref += `${pad(offsets[i])} 00000 n \n`;
        add(xref);
        add(`trailer <</Root 1 0 R /Size 6>>\nstartxref\n${xrefPos}\n%%EOF`);

        const bytes = parts.map(s=>enc(s));
        return new Blob(bytes, {type:'application/pdf'});
      }

      function downloadProof(){
        const name = studentName() || "Student";
        const dateStr = new Date().toLocaleDateString();
        const line = `Proof of Completion for ${name} on ${dateStr}`;
        const blob = makeProofPDF(line);
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "SUD_Proof_of_Completion.pdf";
        document.body.appendChild(a); a.click(); a.remove();
        setTimeout(()=>URL.revokeObjectURL(url), 1000);
      }

      function lockApp(){
        LOCKED = true;
        $("lockOverlay").style.display = "flex";
        document.querySelectorAll("button, input, select, textarea").forEach(el => { el.disabled = true; });
      }

      function showModal(title, html, onOk){
        $("modalTitle").textContent = title; $("modalBody").innerHTML = html; $("modal").classList.remove("hidden");
        const handler = ()=>{ $("modal").classList.add("hidden"); if (typeof onOk==="function") onOk(); $("modalOk").removeEventListener("click", handler); };
        $("modalOk").addEventListener("click", handler);
      }

      $("resetBtn").addEventListener("click", ()=>{
        if (LOCKED) return;
        if (confirm("Reset the current case? Progress will be cleared.")){
          setCase(state.caseKey);
        }
      });

      // Start with first case automatically.
      setCase("cannabis");
    });
  })();
  </script>
</body>
</html>