File size: 59,301 Bytes
6b5a5cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>PDF Slide Viewer · Styled</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.min.js"></script>
  <style>
    :root{
      --bg-1:#0b0f14;          /* page background */
      --bg-2:#0e131a;          /* canvas background */
      --panel:rgba(18, 22, 30, .6);
      --panel-2:rgba(18, 22, 30, .85);
      --border:rgba(255,255,255,.08);
      --accent:#5cc8ff;        /* primary accent */
      --accent-2:#a78bfa;      /* secondary accent */
      --text:#eef2f7;          /* primary text */
      --muted:#a3b0c2;         /* muted text */
      --danger:#ff6b6b;
      --shadow:0 10px 30px rgba(0,0,0,.35);
      --radius:14px;
    }
    *{box-sizing:border-box}
    html,body{height:100%}
    body{
      margin:0;
      overflow:hidden;
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji";
      background: radial-gradient(1200px 800px at 70% 10%, rgba(92,200,255,.08), transparent 60%),
                  radial-gradient(900px 900px at 10% 80%, rgba(167,139,250,.08), transparent 60%),
                  var(--bg-1);
      color:var(--text);
      -webkit-font-smoothing:antialiased;
      -moz-osx-font-smoothing:grayscale;
      user-select:none;
    }
    /* Canvas layer */
    #canvas-container{ position:absolute; inset:0; display:flex; justify-content:center; align-items:center; }
    canvas{
      position:absolute; top:50%; left:50%; transform:translate(-50%,-50%);
      background:linear-gradient(180deg, var(--bg-2), #141a23);
      border-radius:18px;
      box-shadow: var(--shadow);
      transition:opacity .35s ease;
    }
    #spotlight-canvas{ z-index:50; display:none; pointer-events:none; background:transparent !important; }
    /* Top-left tool dock */
    .toolbar{
      position:absolute; top:20px; left:16px; z-index:20;
      display:flex; flex-direction:column; gap:10px;
      padding:10px; border-radius:var(--radius);
      background: var(--panel);
      border: 1px solid var(--border);
      backdrop-filter: blur(10px);
      box-shadow: var(--shadow);
    }
    .toolbar-section{ display:flex; flex-direction:column; align-items:center; gap:8px; padding-bottom:8px; border-bottom:1px solid var(--border); }
    .toolbar-section:last-child{ border-bottom:none; padding-bottom:0; }
    .toolbar button{
      width:36px; height:36px; border:none; border-radius:12px; cursor:pointer; color:var(--text);
      background:linear-gradient(180deg, rgba(255,255,255,.06), rgba(255,255,255,.02));
      outline:1px solid var(--border);
      box-shadow: inset 0 1px 0 rgba(255,255,255,.06);
      transition: transform .12s ease, outline-color .2s ease, background .2s ease;
    }
    .toolbar button:hover{ transform: translateY(-1px); background:linear-gradient(180deg, rgba(255,255,255,.12), rgba(255,255,255,.04)); }
    .toolbar button:active{ transform: translateY(0); }
    .drawing-tool.active{
      background:linear-gradient(180deg, rgba(92,200,255,.35), rgba(92,200,255,.15));
      outline-color: rgba(92,200,255,.65);
      box-shadow: 0 0 0 2px rgba(92,200,255,.25), inset 0 1px 0 rgba(255,255,255,.12);
    }
    .color-button{ width:26px; height:22px; border-radius:6px; border:2px solid #fff; opacity:.95; }
    .color-button.red{ background:#ff3b30; border-color:#ffc7c3; }
    .color-button.green{ background:#34c759; border-color:#c6f5d5; }
    .color-button.blue{ background:#0a84ff; border-color:#c7e1ff; }
    .color-button.yellow{ background:#ffd60a; border-color:#fff0a3; }
    .color-button.orange{ background:#ff9f0a; border-color:#ffe0b8; }
    .color-button.active-color{ outline:2px solid var(--accent); transform:scale(1.08); }
    .arrow-button{
      position:absolute; top:50%; transform:translateY(-50%);
    }
    .small-arrow {
      font-size: 11px !important;
      width: 20px !important;
      height: 20px !important;
      padding: 2px !important;
      min-width: 0 !important;
      min-height: 0 !important;
    }
    .arrow-button:hover{ transform: translateY(-50%) scale(1.06); background:linear-gradient(180deg, rgba(255,255,255,.12), rgba(255,255,255,.04)); }
    #prev-slide{ left:14px } #next-slide{ right:14px }
    .slider-container{
      position:static; display:flex; gap:6px; align-items:center;
      padding:8px 10px; border-radius:12px;
      background: var(--panel);
      border:1px solid var(--border);
      backdrop-filter: blur(8px);
      box-shadow: var(--shadow);
    }
    #page-slider{ width:140px }
    input[type="range"]{ appearance:none; height:6px; border-radius:999px; background:rgba(255,255,255,.15); outline:none }
    input[type="range"]::-webkit-slider-thumb{ appearance:none; width:16px; height:16px; border-radius:50%; background:var(--accent); box-shadow:0 2px 6px rgba(92,200,255,.4) }
    input[type="number"], #timer-input{
      width:48px; padding:5px 6px; border-radius:10px; border:1px solid var(--border);
    }
    .small-indicator {
      font-size: 10px !important;
      padding: 2px 5px !important;
      box-shadow: 0 2px 6px rgba(167,139,250,.13) !important;
      border-radius: 999px;
      font-weight: 600;
      letter-spacing: .2px;
      color: var(--text);
      background: linear-gradient(180deg, rgba(167,139,250,.18), rgba(167,139,250,.08));
      border: 1px solid rgba(167,139,250,.35);
      display: flex;
      align-items: center;
      justify-content: center;
    }
    /* Links panel */
    .links-container{
      position:static; max-height:30vh; overflow:auto;
      display:flex; flex-direction:column; gap:8px; padding:12px; border-radius:var(--radius);
      background: var(--panel-2);
      border:1px solid var(--border);
      backdrop-filter: blur(12px);
      box-shadow: var(--shadow);
    }
    .links-container::before{
      content:"Links"; display:block; font-size:12px; letter-spacing:.08em; text-transform:uppercase; color:var(--muted);
      margin:2px 2px 8px;
    }
    .links-container a{
      width:100%;
      justify-content:space-between;
      color: #fff !important;
      text-decoration: underline;
      transition: color 0.2s;
    }
    .links-container a:visited {
      color: #fff !important;
    }
    .links-container a:hover {
      color: #5cc8ff !important;
    }
    /* Clock & Timer */
    #clock-container{
      position:absolute; top:20px; right:20px; z-index:25; color:var(--text);
      background: var(--panel);
      border:1px solid var(--border);
      border-radius:var(--radius);
  padding:8px; width:130px; text-align:center; backdrop-filter: blur(10px); box-shadow: var(--shadow);
    }
    /* Smaller idle display (less intrusive) */
    #clock-display{
      font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
      font-weight:700; font-size:13px; letter-spacing:.3px; margin-bottom:4px;
    }
    #timer-setup .timer-row {
      gap: 4px !important;
    }
    #timer-input, #timer-message-input {
  font-size: 11px !important;
  padding: 2px 4px !important;
  height: 22px !important;
  border-radius: 7px !important;
  width: 38px;
  background: transparent !important;
  color: var(--text) !important;
  box-shadow: none !important;
  border: 1.5px solid #b5c6e0 !important;
  transition: border-color 0.2s;
}

#timer-input:focus, #timer-message-input:focus {
  border-color: #5cc8ff !important;
    }
    #timer-message-input {
  width: 70px;
    }
    #timer-start-btn {
      font-size: 11px !important;
      padding: 2px 8px !important;
      border-radius: 7px !important;
      height: 22px !important;
    }
    #timer-controls button {
      font-size: 11px !important;
      padding: 2px 8px !important;
      border-radius: 7px !important;
      height: 22px !important;
    }
    #timer-controls button, #timer-setup button{
      padding:6px 10px; border-radius:10px; border:1px solid var(--border); color:var(--text);
      background: linear-gradient(180deg, rgba(255,255,255,.08), rgba(255,255,255,.02)); cursor:pointer;
    }
    /* File loader */
    #file-loader{ position:absolute; top:20px; left:50%; transform:translateX(-50%); z-index:25 }
    #pdf-upload{ display:none }
    /* Welcome */
    #welcome-screen{
      position:absolute; inset:0; display:flex; align-items:center; justify-content:center; z-index:5;
      color:#cfd6e4; font-size:22px; text-align:center; pointer-events:none;
    }
    #welcome-screen p{
      background: var(--panel-2); border:1px solid var(--border); border-radius:18px; padding:18px 22px; backdrop-filter: blur(10px);
      box-shadow: var(--shadow);
    }
    /* Page indicator */
    #page-indicator{
      position:absolute; right:18px; bottom:18px;
      padding:8px 12px; border-radius:999px; font-weight:600; letter-spacing:.3px; color:var(--text);
      background: linear-gradient(180deg, rgba(167,139,250,.18), rgba(167,139,250,.08));
      border:1px solid rgba(167,139,250,.35); box-shadow:0 6px 20px rgba(167,139,250,.2);
      z-index:1200;
    }
    /* Scrollbar aesthetics (WebKit) */
    .links-container::-webkit-scrollbar{ width:10px }
    .links-container::-webkit-scrollbar-track{ background:rgba(255,255,255,.04); border-radius:10px }
    .links-container::-webkit-scrollbar-thumb{ background:linear-gradient(var(--accent), var(--accent-2)); border-radius:10px }
    .hidden{ display:none !important }
  
    /* --- Interaction & z-index overrides --- */
    #canvas-container{ z-index:0 }
    #pdf-canvas-1, #pdf-canvas-2{ z-index:1 }
    .toolbar, .arrow-button, #fullscreen-btn, #file-loader{ z-index:1000; pointer-events:auto }
    .links-container{ z-index:900 }
    #welcome-screen{ z-index:5; pointer-events:none }
  
    /* --- Small link buttons & compact links panel --- */
    .link-button{ padding:6px 8px; border-radius:8px; font-size:12px; }
    .link-icon{ width:12px; height:12px; }
    .links-container{ width:220px; gap:6px; padding:10px; }
  
    /* Bottom bar layout */
    .bottom-bar{ position:absolute; bottom:16px; left:12px; z-index:20; display:flex; align-items:flex-end; gap:10px; }
  
    /* Timer message UI (type-in only) */
    #timer-message-input{ width:160px; padding:6px 8px; border-radius:10px; border:1px solid var(--border); background: rgba(255,255,255,.04); color:var(--text); outline:none; box-shadow: inset 0 1px 0 rgba(255,255,255,.06); }
  
    /* Full-screen banner for timer message */
    #timer-banner{ position:absolute; top:0; left:0; right:0; bottom:auto; display:flex; align-items:flex-start; justify-content:center; padding-top:4vh; z-index:1100; pointer-events:none; }
    #timer-banner-text{ width:min(92vw, 1600px); text-align:center; font-weight:800; font-size:clamp(28px, 7vw, 120px); line-height:1.05; letter-spacing:.03em; text-transform:uppercase; color:rgba(255,255,255,.95); text-shadow:0 6px 30px rgba(0,0,0,.6); background:linear-gradient(180deg, rgba(92,200,255,.18), rgba(92,200,255,.08)); padding:.15em .5em; border-radius:16px; border:1px solid rgba(255,255,255,.18); }
    /* Large clock when timer is running (kept) */
    #clock-container.running{ width:280px; padding:14px; }
    #clock-container.running #clock-display{ font-size:64px; }

    /* Whiteboard slide-in panel */
    #whiteboard{
      position:fixed; top:0; right:0; width:100vw; height:100vh; z-index:2200;
      transform:translateX(100%); transition:transform .35s ease; display:flex; flex-direction:column; background:#ffffff; color:#111;
      box-shadow: 0 30px 80px rgba(0,0,0,.6);
    }
    #whiteboard.open{ transform:translateX(0); }
    .wb-toolbar{ display:flex; align-items:center; gap:12px; padding:10px 14px; background:#111; color:#fff; height:56px; position:absolute; top:0; left:0; right:0; z-index:2400; box-shadow: 0 6px 20px rgba(0,0,0,.25); }
    .wb-toolbar .wb-left{ display:flex; gap:8px; align-items:center; }
    .wb-toolbar button{ border:none; background:transparent; color:inherit; padding:8px 10px; border-radius:8px; cursor:pointer; }
    .wb-controls{ margin-left:auto; display:flex; gap:10px; align-items:center; }
    .wb-color{ width:20px; height:20px; border-radius:6px; border:1px solid rgba(0,0,0,.06); cursor:pointer; }
    #whiteboard-canvas{ flex:1; background:#fff; touch-action:none; margin-top:56px; }
    .wb-input-range{ width:120px; }
  </style>
</head>
<body>
  <div id="canvas-container">
    <canvas id="pdf-canvas-1"></canvas>
    <canvas id="pdf-canvas-2"></canvas>
  </div>
  <canvas id="spotlight-canvas"></canvas>

  <!-- Tool Dock -->
  <div class="toolbar main-tool">
    <div class="toolbar-section">
      <button id="tool-pen" class="drawing-tool active" title="Pen Tool (T)">✏️</button>
      <button id="tool-rectangle" class="drawing-tool" title="Draw Rectangle (D)"></button>
      <button id="tool-spotlight" class="drawing-tool" title="Spotlight (S)">🔦</button>
    </div>
    <div class="toolbar-section">
      <button id="thickness-increase" title="Increase Size (+)"></button>
      <button id="thickness-decrease" title="Decrease Size (-)"></button>
    </div>
    <div class="toolbar-section">
      <button class="color-button red" data-color="red" title="Red (R)"></button>
      <button class="color-button green" data-color="green" title="Green (G)"></button>
      <button class="color-button blue" data-color="blue" title="Blue (B)"></button>
      <button class="color-button yellow" data-color="yellow" title="Yellow (Y)"></button>
      <button class="color-button orange" data-color="orange" title="Orange (O)"></button>
    </div>
    <div class="toolbar-section">
      <button id="clear-draw" title="Clear All Drawings (E)">🧹</button>
    </div>
  </div>

  <!-- Bottom bar: Links (toggle with L) + Slider -->
  <div id="bottom-bar" class="bottom-bar main-tool">
    <div id="links-container" class="links-container"></div>
    <div class="slider-container">
      <input type="range" id="page-slider" min="1" max="1" value="1" />
      <input type="number" id="page-number-input" min="1" value="1" />
    </div>
  </div>


  <!-- File chooser -->
  <div id="file-loader">
    <label for="pdf-upload" class="link-button">
      <svg class="link-icon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M12 3a1 1 0 0 1 1 1v8.586l2.293-2.293a1 1 0 1 1 1.414 1.414l-4 4a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L11 12.586V4a1 1 0 0 1 1-1Zm-7 14a1 1 0 0 1 1-1h12a1 1 0 1 1 0 2H6a1 1 0 0 1-1-1Z"/></svg>
      Open PDF
    </label>
    <input type="file" id="pdf-upload" accept="application/pdf,.pdf" />
  </div>

  <!-- Clock & Timer -->
  <div id="clock-container">
    <div id="clock-display">00:00:00</div>
    <div id="timer-setup">
      <div class="timer-row" style="display:flex; gap:8px; justify-content:center; align-items:center;">
        <input type="number" id="timer-input" min="1" />
        <input type="text" id="timer-message-input" />
        <button id="timer-start-btn">Start</button>
      </div>
      <!-- Presets removed -->
    </div>
    <div id="timer-controls" style="display:none">
      <button id="timer-pause-btn">Pause</button>
      <button id="timer-stop-btn">Stop</button>
    </div>
  </div>

  <!-- Slide navigation arrows and page indicator (bottom right) -->
  <div id="slide-nav-bar" style="position:absolute; right:18px; bottom:18px; z-index:1201; display:flex; align-items:center; gap:8px;">
    <button id="prev-slide" class="arrow-button small-arrow" title="Previous Slide" aria-label="Previous Slide" style="position:static;">&#8592;</button>
    <div id="page-indicator" class="small-indicator" style="position:static;">1 / 1</div>
    <button id="next-slide" class="arrow-button small-arrow" title="Next Slide" aria-label="Next Slide" style="position:static;">&#8594;</button>
  </div>

  <!-- Welcome overlay -->
  <div id="welcome-screen"><p>Please select a PDF to begin</p></div>

  <!-- Timer banner -->
  <div id="timer-banner" class="hidden"><div id="timer-banner-text"></div></div>

  <script>
    console.info('[PDF Viewer] ready v2.0');
    if (window.pdfjsLib) {
      pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js';
    } else {
      console.error('PDF.js failed to load.');
      const ws = document.getElementById('welcome-screen');
      if (ws) { ws.textContent = 'PDF.js failed to load. Check your network connection and reload.'; }
    }
    // --- 1. DOM ---
    const mainTools = document.querySelectorAll('.main-tool');
    const canvases = [document.getElementById('pdf-canvas-1'), document.getElementById('pdf-canvas-2')];
    const ctxs = [canvases[0].getContext('2d'), canvases[1].getContext('2d')];
    const spotlightCanvas = document.getElementById('spotlight-canvas');
    const spotlightCtx = spotlightCanvas.getContext('2d');
    const toolSpotlightBtn = document.getElementById('tool-spotlight');
  const prevSlideBtn = document.getElementById('prev-slide');
  const nextSlideBtn = document.getElementById('next-slide');
    const linksContainer = document.getElementById('links-container');
    const clearDrawBtn = document.getElementById('clear-draw');
    const colorButtons = document.querySelectorAll('.color-button[data-color]');
    const pageSlider = document.getElementById('page-slider');
    const pageNumberInput = document.getElementById('page-number-input');
    const pdfUploadInput = document.getElementById('pdf-upload');
    const pdfFileLoader = document.getElementById('file-loader');
    const openPdfLabel = document.querySelector('label[for="pdf-upload"]');
    if (pdfUploadInput) {
      pdfUploadInput.addEventListener('click', () => { pdfUploadInput.value = ''; });
    }
    if (openPdfLabel) {
      const triggerPicker = () => { if (pdfUploadInput) { pdfUploadInput.value = ''; pdfUploadInput.click(); } };
      openPdfLabel.addEventListener('click', (e) => { e.preventDefault(); triggerPicker(); });
      openPdfLabel.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); triggerPicker(); } });
    }
    const toolPenBtn = document.getElementById('tool-pen');
    const toolRectangleBtn = document.getElementById('tool-rectangle');
    const thicknessIncreaseBtn = document.getElementById('thickness-increase');
    const thicknessDecreaseBtn = document.getElementById('thickness-decrease');
    const drawingToolBtns = document.querySelectorAll('.drawing-tool');
    const clockContainer = document.getElementById('clock-container');
    const clockDisplay = document.getElementById('clock-display');
    const timerInput = document.getElementById('timer-input');
    const timerSetupDiv = document.getElementById('timer-setup');
    const timerControlsDiv = document.getElementById('timer-controls');
    const timerStartBtn = document.getElementById('timer-start-btn');
    const timerPauseBtn = document.getElementById('timer-pause-btn');
    const timerStopBtn = document.getElementById('timer-stop-btn');
    const timerMessageInput = document.getElementById('timer-message-input');
    const timerBanner = document.getElementById('timer-banner');
    const timerBannerText = document.getElementById('timer-banner-text');
    const welcomeScreen = document.getElementById('welcome-screen');
    const pageIndicator = document.getElementById('page-indicator');
    // --- 2. State ---
    let pdfDoc = null, currentPage = 1, totalPages = 0;
    let isDrawing = false;
    let drawColor = 'red';
    let activeCanvasIndex = 0, isTransitioning = false;
    let lastX = 0, lastY = 0;
    let currentTool = 'pen';
    let lineWidth = 4;
    let shapeStartX = 0, shapeStartY = 0;
    let shapeSnapshot = null;
    let spotlightMode = false;
    let clockInterval, timerInterval, timerState = 'stopped', timerRemainingTime = 0;
    let queuedPage = null;
    function normalizeUrl(u){
      try{ const url = new URL(u); url.hash=''; url.host=url.host.toLowerCase(); url.pathname=url.pathname.replace(/\/+$/, ''); return url.toString(); }
      catch{ return (u||'').trim().toLowerCase().replace(/\/+$/, ''); }
    }
    function makeLinkLabel(url, title){ if(title) return title; try{ return new URL(url).hostname }catch{ return url } }
    function addLinkButton(url, title, perPageSeen){
      const norm = normalizeUrl(url); if(perPageSeen.has(norm)) return; perPageSeen.add(norm);
      const a = document.createElement('a');
      a.href = url; a.target = '_blank'; a.rel = 'noopener noreferrer'; a.className = 'link-button';
      a.innerHTML = `<span>${makeLinkLabel(url, title) || 'Link'}</span>
        <svg class="link-icon" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M14 3h7v7h-2V6.414l-7.293 7.293a1 1 0 1 1-1.414-1.414L17.586 5H14V3ZM5 5h5a1 1 0 1 1 0 2H6v10h10v-4a1 1 0 1 1 2 0v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z"/></svg>`;
      linksContainer.appendChild(a);
    }
    async function renderPdfPage(pageNumber, canvas, context){
      if(!pdfDoc) return;
      linksContainer.innerHTML = '';
      const perPageSeen = new Set();
      const page = await pdfDoc.getPage(pageNumber);
      const pdfViewport = page.getViewport({ scale:1.0 });
      const scale = Math.min(window.innerWidth / pdfViewport.width, window.innerHeight / pdfViewport.height);
      const viewport = page.getViewport({ scale });
      canvas.width = viewport.width; canvas.height = viewport.height;
      canvas.style.width = `${viewport.width}px`; canvas.style.height = `${viewport.height}px`;
      const renderContext = { canvasContext: context, viewport };
      await page.render(renderContext).promise;
      if (canvas === canvases[activeCanvasIndex]){
        const annotations = await page.getAnnotations();
        annotations.forEach(ann => { if(ann && ann.url) addLinkButton(ann.url, ann.title, perPageSeen); });
      }
      pageIndicator.textContent = `${pageNumber} / ${totalPages || 1}`;
    }
    async function loadPdf(pdfSource){
      try{
        if (!window.pdfjsLib) throw new Error('PDF.js not available');
        const isLocalFile = location && location.protocol === 'file:';
        let loadingTask;
        if (pdfSource instanceof ArrayBuffer) {
          loadingTask = pdfjsLib.getDocument({ data: new Uint8Array(pdfSource), disableWorker: isLocalFile });
        } else if (pdfSource && typeof pdfSource.byteLength === 'number') {
          loadingTask = pdfjsLib.getDocument({ data: new Uint8Array(pdfSource), disableWorker: isLocalFile });
        } else if (typeof pdfSource === 'string') {
          loadingTask = pdfjsLib.getDocument({ url: pdfSource, disableWorker: isLocalFile });
        } else {
          throw new Error('Unsupported PDF source');
        }
        welcomeScreen.textContent = 'Loading...';
        const doc = await loadingTask.promise;
        pdfDoc = doc;
        linksContainer.innerHTML = '';
        totalPages = pdfDoc.numPages; currentPage = 1;
        pageSlider.max = totalPages; pageSlider.value = 1;
        pageNumberInput.max = totalPages; pageNumberInput.value = 1;
        pageIndicator.textContent = `1 / ${totalPages}`;
        canvases[0].style.zIndex = 1; canvases[0].style.opacity = '1';
        canvases[1].style.zIndex = 0; canvases[1].style.opacity = '0';
        activeCanvasIndex = 0;
        await renderPdfPage(currentPage, canvases[0], ctxs[0]);
        if (prevSlideBtn) prevSlideBtn.disabled = currentPage === 1;
        if (nextSlideBtn) nextSlideBtn.disabled = currentPage === totalPages;
        welcomeScreen.style.display = 'none';
      }catch(error){
        console.error('Error loading PDF:', error);
        const msg = (error && error.message) ? error.message : 'Failed to load PDF. Please try another file.';
        welcomeScreen.textContent = `Failed to load PDF: ${msg}`;
        welcomeScreen.style.display = 'block';
        pdfDoc = null;
      }
    }
    async function transitionToPage(pageNumber){
      if(isTransitioning || !pdfDoc) return; isTransitioning = true;
      const oldCanvasIndex = activeCanvasIndex; const newCanvasIndex = 1 - oldCanvasIndex;
      const oldCanvas = canvases[oldCanvasIndex]; const newCanvas = canvases[newCanvasIndex];
      activeCanvasIndex = newCanvasIndex;
      await renderPdfPage(pageNumber, newCanvas, ctxs[newCanvasIndex]);
      newCanvas.style.zIndex = 1; oldCanvas.style.zIndex = 0;
      newCanvas.style.opacity = '1'; oldCanvas.style.opacity = '0';
      currentPage = pageNumber;
      setTimeout(() => {
        isTransitioning = false;
        if (queuedPage && queuedPage !== currentPage) {
          const next = queuedPage; queuedPage = null;
          transitionToPage(next);
        }
      }, 350);
      if (prevSlideBtn) prevSlideBtn.disabled = currentPage === 1;
      if (nextSlideBtn) nextSlideBtn.disabled = currentPage === totalPages;
      pageSlider.value = currentPage; pageNumberInput.value = currentPage;
    }
    function setDrawColor(newColor){ drawColor = newColor; colorButtons.forEach(btn => btn.classList.remove('active-color')); const btn = document.querySelector(`.color-button[data-color="${newColor}"]`); if(btn) btn.classList.add('active-color'); }
    function changeThickness(amount){ lineWidth = Math.max(2, Math.min(50, lineWidth + amount)); }
    function setTool(tool){ if(spotlightMode) toggleSpotlightMode(false); currentTool = tool; drawingToolBtns.forEach(btn => btn.classList.remove('active')); const t=document.getElementById(`tool-${tool}`); if(t) t.classList.add('active'); }
    function drawSpotlight(e){
      spotlightCtx.clearRect(0,0,spotlightCanvas.width,spotlightCanvas.height);
      spotlightCtx.fillStyle = 'rgba(0,0,0,.82)';
      spotlightCtx.fillRect(0,0,spotlightCanvas.width,spotlightCanvas.height);
      spotlightCtx.globalCompositeOperation = 'destination-out';
      spotlightCtx.beginPath(); spotlightCtx.arc(e.pageX, e.pageY, 110, 0, Math.PI*2); spotlightCtx.fill();
      spotlightCtx.globalCompositeOperation = 'source-over';
    }
    function toggleSpotlightMode(forceState){
      spotlightMode = forceState !== undefined ? forceState : !spotlightMode;
      if(spotlightMode){
        drawingToolBtns.forEach(btn => btn.classList.remove('active')); toolSpotlightBtn.classList.add('active');
        spotlightCanvas.width = window.innerWidth; spotlightCanvas.height = window.innerHeight; spotlightCanvas.style.display='block';
        window.addEventListener('mousemove', drawSpotlight);
      }else{
        spotlightCanvas.style.display='none'; window.removeEventListener('mousemove', drawSpotlight);
        if(toolSpotlightBtn.classList.contains('active')) setTool('pen');
      }
    }
    const goToPage = (num)=>{
      if(!pdfDoc || num < 1 || num > totalPages || num === currentPage) return;
      if (isTransitioning) { queuedPage = num; return; }
      transitionToPage(num);
    };
    const clearDrawing = ()=>{ if(pdfDoc) renderPdfPage(currentPage, canvases[activeCanvasIndex], ctxs[activeCanvasIndex]); };
    const stopDrawing = ()=>{
      if(!isDrawing) return; isDrawing=false; const ctx=ctxs[activeCanvasIndex];
      if(currentTool==='pen'){ ctx.closePath(); }
      else if(currentTool==='rectangle'){ ctx.putImageData(shapeSnapshot,0,0); ctx.strokeStyle=drawColor; ctx.lineWidth=lineWidth; ctx.strokeRect(shapeStartX, shapeStartY, lastX-shapeStartX, lastY-shapeStartY); }
    };
    if (pdfUploadInput) {
      pdfUploadInput.addEventListener('change', (e)=>{
        const file = e.target.files && e.target.files[0];
        if (!file) return;
        const isPdf = (file.type === 'application/pdf') || (file.name && file.name.toLowerCase().endsWith('.pdf'));
        if (!isPdf) {
          welcomeScreen.textContent = 'Please choose a PDF file (.pdf).';
          welcomeScreen.style.display = 'block';
          e.target.value = '';
          return;
        }
        const reader = new FileReader();
        reader.onload = (ev) => { loadPdf(ev.target.result); };
        reader.onerror = () => { welcomeScreen.textContent = 'Could not read the file.'; welcomeScreen.style.display = 'block'; };
        reader.onloadend = () => { e.target.value = ''; };
        reader.readAsArrayBuffer(file);
      });
    }
    toolPenBtn.addEventListener('click', ()=>setTool('pen'));
    toolRectangleBtn.addEventListener('click', ()=>setTool('rectangle'));
    toolSpotlightBtn.addEventListener('click', ()=>toggleSpotlightMode());
    thicknessIncreaseBtn.addEventListener('click', ()=>changeThickness(2));
    thicknessDecreaseBtn.addEventListener('click', ()=>changeThickness(-2));
    document.addEventListener('keydown', (event)=>{
      const tag = (event.target && event.target.tagName ? event.target.tagName.toLowerCase() : '');
      const isTextInput = tag === 'input' || tag === 'textarea' || tag === 'select' || (event.target && event.target.isContentEditable);
      if (event.key === 'ArrowLeft' || event.key === 'ArrowRight'){
        event.preventDefault();
        if (event.key === 'ArrowLeft') goToPage(currentPage - 1); else goToPage(currentPage + 1);
        if (event.target === pageSlider || event.target === pageNumberInput) {
          event.target.blur();
        }
        return;
      }
      if(isTextInput) return;
      switch(event.key){
        case 'e': clearDrawing(); break;
        case 'd': setTool('rectangle'); break;
        case 's': toggleSpotlightMode(); break;
        case 't': setTool('pen'); break;
        case '+': changeThickness(2); break;
        case '-': changeThickness(-2); break;
        case 'h':
          mainTools.forEach(el => { if (el.id !== 'bottom-bar') el.classList.toggle('hidden'); });
          const bottomBar = document.getElementById('bottom-bar');
          if (bottomBar) { const sliderWrap = bottomBar.querySelector('.slider-container'); if (sliderWrap) sliderWrap.classList.toggle('hidden'); }
          break;
        case 'f':
          if (!document.fullscreenElement) {
            document.documentElement.requestFullscreen().catch(err=>console.error(err));
          } else {
            document.exitFullscreen();
          }
          break;
        case 'c': clockContainer.classList.toggle('hidden'); break;
        case 'p': pdfFileLoader.classList.toggle('hidden'); break;
        case 'r': setDrawColor('red'); break;
        case 'g': setDrawColor('green'); break;
        case 'b': setDrawColor('blue'); break;
        case 'y': setDrawColor('yellow'); break;
        case 'o': setDrawColor('orange'); break;
        case 'l':
        case 'L':
          linksContainer.classList.toggle('hidden');
          break;
      }
    });
    canvases.forEach((canvas, index)=>{
      canvas.addEventListener('mousedown', e=>{
        if(index!==activeCanvasIndex || spotlightMode) return; isDrawing=true; const ctx=ctxs[activeCanvasIndex];
        if(currentTool==='pen'){
          [lastX,lastY] = [e.offsetX, e.offsetY]; ctx.beginPath(); ctx.moveTo(lastX,lastY);
          ctx.strokeStyle=drawColor; ctx.lineWidth=lineWidth; ctx.lineCap='round'; ctx.lineJoin='round';
        } else if(currentTool==='rectangle'){
          shapeSnapshot = ctx.getImageData(0,0,canvas.width,canvas.height);
          [shapeStartX,lastX] = [e.offsetX, e.offsetX]; [shapeStartY,lastY] = [e.offsetY, e.offsetY];
        }
      });
      canvas.addEventListener('mousemove', e=>{
        if(!isDrawing || index!==activeCanvasIndex || spotlightMode) return; const ctx=ctxs[activeCanvasIndex];
        if(currentTool==='pen'){
          ctx.lineTo(e.offsetX, e.offsetY); ctx.stroke(); [lastX,lastY] = [e.offsetX, e.offsetY];
        } else if(currentTool==='rectangle'){
          ctx.putImageData(shapeSnapshot,0,0); ctx.strokeStyle=drawColor; ctx.lineWidth=lineWidth;
          ctx.strokeRect(shapeStartX, shapeStartY, e.offsetX-shapeStartX, e.offsetY-shapeStartY);
          [lastX,lastY] = [e.offsetX, e.offsetY];
        }
      });
    });
    window.addEventListener('mouseup', stopDrawing);
    window.addEventListener('blur', stopDrawing);
    window.addEventListener('resize', ()=>{
      if(pdfDoc) renderPdfPage(currentPage, canvases[activeCanvasIndex], ctxs[activeCanvasIndex]);
      if(spotlightMode){ spotlightCanvas.width = window.innerWidth; spotlightCanvas.height = window.innerHeight; }
    });
    clearDrawBtn.addEventListener('click', clearDrawing);
    colorButtons.forEach(btn=>btn.addEventListener('click', ()=>setDrawColor(btn.dataset.color)));
  if (prevSlideBtn) prevSlideBtn.addEventListener('click', ()=>goToPage(currentPage-1));
  if (nextSlideBtn) nextSlideBtn.addEventListener('click', ()=>goToPage(currentPage+1));
    pageSlider.addEventListener('input', e=>goToPage(parseInt(e.target.value,10)));
    pageNumberInput.addEventListener('change', e=>goToPage(parseInt(e.target.value,10)));
    /* ---- Clock & Timer ---- */
    function showBanner(text){ if(!timerBanner || !timerBannerText) return; timerBannerText.textContent = text; timerBanner.classList.remove('hidden'); }
    function hideBanner(){ if(!timerBanner) return; timerBanner.classList.add('hidden'); }
    function playEndBeeps(count=1){
      let beepsPlayed=0; const audioCtx = new (window.AudioContext||window.webkitAudioContext)();
      function beep(){ if(beepsPlayed>=count) return; const osc=audioCtx.createOscillator(); osc.type='sine'; osc.frequency.setValueAtTime(880, audioCtx.currentTime);
        osc.connect(audioCtx.destination); osc.start(); osc.stop(audioCtx.currentTime+0.3); beepsPlayed++; setTimeout(beep, 500); }
      beep();
    }
    function displayTime(ms){ if(ms<0) ms=0; const mins=Math.floor(ms/60000); const secs=Math.floor((ms%60000)/1000); clockDisplay.textContent = `${String(mins).padStart(2,'0')}:${String(secs).padStart(2,'0')}`; }
    function startClock(){ clearInterval(timerInterval); const update=()=>clockDisplay.textContent=new Date().toLocaleTimeString(); update(); clockInterval=setInterval(update, 1000); }
    function runTimer(duration){
      clearInterval(clockInterval);
      const endTime=Date.now()+duration;
      timerState='running';
      timerInterval=setInterval(()=>{
        timerRemainingTime=endTime-Date.now();
        if(timerRemainingTime<=0){
          playEndBeeps(3);
          stopTimer();               // ensures UI reset + Start visible
        } else {
          displayTime(timerRemainingTime);
        }
      }, 250);
      displayTime(duration);
    }
    // ✅ Strong reset so Start always returns
    function stopTimer(){
      clearInterval(timerInterval);
      timerState='stopped';
      timerRemainingTime=0;
      // UI reset
      timerControlsDiv.style.display='none';
      timerSetupDiv.style.display='flex';   // keep original layout
      timerPauseBtn.textContent='Pause';
      clockContainer.classList.remove('running');
      hideBanner();
      // restore live clock
      startClock();
      // ready for next run
      if (timerInput) timerInput.value = '';
      if (timerMessageInput) timerMessageInput.value = '';
      setTimeout(() => timerInput && timerInput.focus(), 0);
    }
    // 🔁 Start from inputs (used by button and Enter key)
    function startFromInputs(){
      const minutes = parseInt(timerInput.value,10);
      const msg = (timerMessageInput && timerMessageInput.value.trim()) || '';
      if(minutes && minutes>0){
        runTimer(minutes*60*1000);
        if (msg) { showBanner(msg); } else { hideBanner(); }
        clockContainer.classList.add('running'); // large clock while running
        timerSetupDiv.style.display='none';
        timerControlsDiv.style.display='flex';
        timerPauseBtn.textContent='Pause';
        timerInput.value='';
      }
    }
    // Start button
    timerStartBtn.addEventListener('click', startFromInputs);
    // Enter in either field starts timer
    [timerInput, timerMessageInput].forEach(el=>{
      el.addEventListener('keydown', (e)=>{
        if (e.key === 'Enter'){
          e.preventDefault();
          startFromInputs();
        }
      });
    });
    timerPauseBtn.addEventListener('click', ()=>{ 
      if(timerState==='running'){
        clearInterval(timerInterval); timerState='paused'; timerPauseBtn.textContent='Resume';
      } else if(timerState==='paused'){
        runTimer(timerRemainingTime); timerState='running'; timerPauseBtn.textContent='Pause';
      }
    });
    timerStopBtn.addEventListener('click', stopTimer);
    // --- 6. Init ---
    function init(){ setDrawColor('red'); setTool('pen'); startClock(); }
    init();
  </script>

  <!-- Whiteboard Panel -->
  <div id="whiteboard" aria-hidden="true">
    <div class="wb-toolbar">
      <div class="wb-left">
        <button id="wb-tool-pen" title="Pen">✏️</button>
        <button id="wb-tool-rect" title="Rectangle"></button>
        <button id="wb-tool-circle" title="Circle"></button>
        <button id="wb-tool-line" title="Line">/</button>
        <button id="wb-back-free" title="Back to Freehand">↩️✏️</button>
        <button id="wb-tool-select" title="Select/Move">🔲</button>
        <button id="wb-bring-front" title="Bring to Front">⬆️</button>
        <button id="wb-send-back" title="Send to Back">⬇️</button>
        <button id="wb-import" title="Import Image">🖼️</button>
        <button id="wb-close" title="Close (X)"></button>
        <button id="wb-undo" title="Undo">↶ Undo</button>
        <button id="wb-clear" title="Clear">🧹 Clear</button>
        <button id="wb-save" title="Save drawing">💾 Save</button>
        <label style="display:flex;align-items:center;gap:8px;color:#fff;margin-left:6px">Size <input id="wb-size" class="wb-input-range" type="range" min="1" max="60" value="6" /></label>
      </div>
      <div class="wb-controls">
        <div id="wb-colors" style="display:flex;gap:8px;align-items:center;">
          <div class="wb-color" data-color="#000000" style="background:#000"></div>
          <div class="wb-color" data-color="#ff3b30" style="background:#ff3b30"></div>
          <div class="wb-color" data-color="#34c759" style="background:#34c759"></div>
          <div class="wb-color" data-color="#0a84ff" style="background:#0a84ff"></div>
          <div class="wb-color" data-color="#ffd60a" style="background:#ffd60a"></div>
        </div>
      </div>
    </div>
    
    <canvas id="whiteboard-canvas"></canvas>
    <input type="file" id="wb-image-input" accept="image/*" style="display:none" />
  </div>
  <script>
    // Whiteboard tools: pen / rect / circle / line / select (move)
    (function(){
      const wb = document.getElementById('whiteboard');
      const canvas = document.getElementById('whiteboard-canvas');
      const ctx = canvas.getContext('2d');
      const closeBtn = document.getElementById('wb-close');
      const clearBtn = document.getElementById('wb-clear');
      const saveBtn = document.getElementById('wb-save');
      const sizeInput = document.getElementById('wb-size');
      const colors = document.getElementById('wb-colors');
      const tools = {
        pen: document.getElementById('wb-tool-pen'),
        rect: document.getElementById('wb-tool-rect'),
        circle: document.getElementById('wb-tool-circle'),
        line: document.getElementById('wb-tool-line'),
        select: document.getElementById('wb-tool-select')
      };

      let deviceRatio = window.devicePixelRatio || 1;
      let tool = 'pen';
      let color = '#000000';
      let lineWidth = parseInt(sizeInput.value,10) || 4;
      let drawing = false;
      let start = {x:0,y:0};
      let shapes = [];
      let current = null;
      let selected = -1;
      let history = [];
      const HANDLE_SIZE = 16; // visual handle size
      const HALF_HANDLE = HANDLE_SIZE / 2;
      let replaceImageIndex = -1;
      const HISTORY_LIMIT = 120;

      function pushHistory(){ try{ const snap = JSON.parse(JSON.stringify(shapes || [])); history.push(snap); if(history.length>HISTORY_LIMIT) history.shift(); }catch(e){ /* ignore */ } }

      function undo(){ if(history.length===0) return; shapes = history.pop() || []; selected = -1; saveShapes(); redraw(); }


      function resize(){ deviceRatio = window.devicePixelRatio || 1; const th = document.querySelector('.wb-toolbar')?.offsetHeight||48; canvas.width = Math.floor(window.innerWidth * deviceRatio); canvas.height = Math.floor((window.innerHeight - th) * deviceRatio); canvas.style.width = window.innerWidth+'px'; canvas.style.height = (window.innerHeight-th)+'px'; ctx.setTransform(deviceRatio,0,0,deviceRatio,0,0); redraw(); }

      function getHandlesForShape(s){ if(!s) return []; if(s.type==='rect' || s.type==='circle'){ const w = s.w||0, h = s.h||0; return [ {name:'nw', x:s.x, y:s.y}, {name:'ne', x:s.x+w, y:s.y}, {name:'se', x:s.x+w, y:s.y+h}, {name:'sw', x:s.x, y:s.y+h} ]; } if(s.type==='line'){ return [ {name:'p1', x:s.x1, y:s.y1}, {name:'p2', x:s.x2, y:s.y2} ]; } return []; }

      function drawHandles(s){ const handles = getHandlesForShape(s); handles.forEach(h=>{ ctx.save(); ctx.fillStyle='white'; ctx.strokeStyle='black'; ctx.lineWidth=1; ctx.fillRect(h.x-HALF_HANDLE,h.y-HALF_HANDLE,HANDLE_SIZE,HANDLE_SIZE); ctx.strokeRect(h.x-HALF_HANDLE,h.y-HALF_HANDLE,HANDLE_SIZE,HANDLE_SIZE); ctx.restore(); }); }

      function redraw(){ ctx.clearRect(0,0,canvas.width/deviceRatio, canvas.height/deviceRatio); shapes.forEach((s, i)=>{ draw(s); if(i===selected) drawHandles(s); }); if(current) draw(current, true); }

      // draw a smoothed pen path (variable-width approximation)
      // Render pen as a continuous solid stroke (no gaps). We approximate variable width
      // by averaging per-point widths for a single stroked path to avoid visible seams.
      function drawSmoothPath(context, path){ if(!path || path.length===0) return; const pts = path; if(pts.length===1){ context.beginPath(); context.arc(pts[0].x, pts[0].y, (pts[0].w||2)/2, 0, Math.PI*2); context.fill(); return; }
        context.lineJoin = 'round'; context.lineCap = 'round';
        // average width to approximate variable pressure while keeping stroke continuous
        let totalW = 0; for(let i=0;i<pts.length;i++) totalW += (pts[i].w || context.lineWidth || 2);
        const avgW = Math.max(1, Math.round(totalW / pts.length));
        context.lineWidth = avgW;
        // build a single continuous stroked path
        context.beginPath(); context.moveTo(pts[0].x, pts[0].y);
        for(let i=1;i<pts.length;i++){ const p = pts[i]; context.lineTo(p.x, p.y); }
        context.stroke();
      }

      function getHandlesForShape(s){ if(!s) return []; if(s.type==='rect' || s.type==='circle' || s.type==='image'){ const w = s.w||0, h = s.h||0; return [ {name:'nw', x:s.x, y:s.y}, {name:'ne', x:s.x+w, y:s.y}, {name:'se', x:s.x+w, y:s.y+h}, {name:'sw', x:s.x, y:s.y+h} ]; } if(s.type==='line'){ return [ {name:'p1', x:s.x1, y:s.y1}, {name:'p2', x:s.x2, y:s.y2} ]; } return []; }

      function draw(s, preview){ if(!s) return; ctx.save(); ctx.strokeStyle = s.color; ctx.fillStyle = s.color; ctx.lineWidth = s.lineWidth||2; if(s.type==='pen'){ if(!s.path || s.path.length===0){ ctx.restore(); return; } drawSmoothPath(ctx, s.path); } else if(s.type==='rect'){ if(s.fill) ctx.fillRect(s.x,s.y,s.w,s.h); ctx.strokeRect(s.x,s.y,s.w,s.h); } else if(s.type==='circle'){ const cx=s.x+s.w/2, cy=s.y+s.h/2, rx=Math.abs(s.w/2), ry=Math.abs(s.h/2); ctx.beginPath(); ctx.ellipse(cx,cy,rx,ry,0,0,Math.PI*2); if(s.fill) ctx.fill(); ctx.stroke(); } else if(s.type==='line'){ ctx.beginPath(); ctx.moveTo(s.x1, s.y1); ctx.lineTo(s.x2, s.y2); ctx.stroke(); } else if(s.type==='image'){ // draw image if available
          if(s._img){ try{ ctx.drawImage(s._img, s.x, s.y, s.w, s.h); }catch(e){ /* ignore draw errors */ } }
          else if(s.src){ // lazy load
            const img = new Image(); img.onload = ()=>{ s._img = img; redraw(); }; img.src = s.src;
          }
        }
        ctx.restore(); }

      function setTool(t){ tool=t; Object.values(tools).forEach(b=>b && b.classList && b.classList.remove('active')); const btn = tools[t]; if(btn) btn.classList.add('active'); updateBackToFreeBtn(); }
      function updateBackToFreeBtn(){ const back = document.getElementById('wb-back-free'); if(!back) return; back.style.display = (tool === 'pen') ? 'none' : 'inline-block'; }
      Object.keys(tools).forEach(k=>{ const b = tools[k]; if(b) b.addEventListener('click', ()=>setTool(k)); });
      colors.querySelectorAll('.wb-color').forEach(c=>c.addEventListener('click', ()=>{ colors.querySelectorAll('.wb-color').forEach(x=>x.style.outline=''); c.style.outline='3px solid rgba(0,0,0,.18)'; color = c.dataset.color || c.style.backgroundColor || '#000'; }));
      sizeInput.addEventListener('input', ()=>{ lineWidth = parseInt(sizeInput.value,10)||4; // update currently selected shape's stroke width if any
        if(selected>=0 && shapes[selected]){ shapes[selected].lineWidth = lineWidth; saveShapes(); redraw(); } });

      function toLocal(e){ const rect = canvas.getBoundingClientRect(); const cx = e.clientX ?? (e.touches && e.touches[0].clientX); const cy = e.clientY ?? (e.touches && e.touches[0].clientY); const pressure = (typeof e.pressure === 'number' ? e.pressure : (e.force || 0)) || 0; return { x: cx - rect.left, y: cy - rect.top, pressure }; }

      function hitTest(p){ // return index of topmost shape under point or -1
        for(let i=shapes.length-1;i>=0;i--){ const s=shapes[i]; if(!s) continue; if(s.type==='rect'){ if(p.x>=s.x && p.x<=s.x+s.w && p.y>=s.y && p.y<=s.y+s.h) return i; } else if(s.type==='circle'){ const cx=s.x+s.w/2, cy=s.y+s.h/2, rx=Math.abs(s.w/2), ry=Math.abs(s.h/2); if(rx>0 && ry>0 && ((p.x-cx)*(p.x-cx)/(rx*rx) + (p.y-cy)*(p.y-cy)/(ry*ry))<=1) return i; } else if(s.type==='line'){ // distance to segment
            const x1=s.x1,y1=s.y1,x2=s.x2,y2=s.y2; const A=p.x-x1, B=p.y-y1, C=x2-x1, D=y2-y1; const dot = A*C + B*D; const len2 = C*C + D*D; let t = (len2===0)?0:dot/len2; t = Math.max(0, Math.min(1, t)); const projx = x1 + t*C, projy = y1 + t*D; const dx = p.x - projx, dy = p.y - projy; const dist2 = dx*dx + dy*dy; if(dist2 <= 9) return i; } else if(s.type==='pen'){ let minx=Infinity,miny=Infinity,maxx=-Infinity,maxy=-Infinity; (s.path||[]).forEach(pt=>{ minx=Math.min(minx,pt.x); miny=Math.min(miny,pt.y); maxx=Math.max(maxx,pt.x); maxy=Math.max(maxy,pt.y); }); if(p.x>=minx-6 && p.x<=maxx+6 && p.y>=miny-6 && p.y<=maxy+6) return i; } }
        return -1;
      }

      canvas.addEventListener('pointerdown', (ev)=>{
        ev.preventDefault(); const p = toLocal(ev); drawing = true; start = p;
        // push history before a change is started
        pushHistory();

        if(tool==='pen'){
          // capture pointer to keep drawing when cursor leaves canvas
          try{ canvas.setPointerCapture(ev.pointerId); }catch(e){}
          const w = Math.max(1, (lineWidth || 2) * (p.pressure || 1));
          // If last shape is a pen with the same settings, continue drawing into it (continuous freehand)
          const last = shapes.length ? shapes[shapes.length-1] : null;
          const PROXIMITY = 20; // px — only append if new stroke starts near the last stroke end
          let appendToLast = false;
          if(last && last.type === 'pen' && last.color === color && (last.lineWidth||0) === (lineWidth||0) && last.path && last.path.length){
            const lp = last.path[last.path.length-1];
            const dx = lp.x - p.x, dy = lp.y - p.y; if((dx*dx + dy*dy) <= (PROXIMITY*PROXIMITY)) appendToLast = true;
          }
          if(appendToLast){ current = last; current.path = current.path || []; current.path.push({ x: p.x, y: p.y, w }); current._isExisting = true; }
          else { current = { type:'pen', path:[{ x:p.x, y:p.y, w }], color, lineWidth }; current._isExisting = false; }
        } else if(tool==='rect' || tool==='circle'){
          current = { type: tool==='rect'?'rect':'circle', x:p.x, y:p.y, w:0, h:0, color, lineWidth, fill:false };
        } else if(tool==='line'){
          current = { type:'line', x1:p.x, y1:p.y, x2:p.x, y2:p.y, color, lineWidth };
        } else if(tool==='select'){
          selected = hitTest(p);
          if(selected<0){ current=null; redraw(); return; }
          // check handles first (larger hitbox)
          const s = shapes[selected]; const handles = getHandlesForShape(s);
          for(const h of handles){ if(p.x>=h.x-HALF_HANDLE && p.x<=h.x+HALF_HANDLE && p.y>=h.y-HALF_HANDLE && p.y<=h.y+HALF_HANDLE){ drawing=false; current={resize:true, handle:h.name, shapeIndex:selected, orig:JSON.parse(JSON.stringify(s)), startPt:p}; canvas.setPointerCapture(ev.pointerId); redraw(); return; } }
          // start moving
          current = { move:true, shapeIndex:selected, startPt:p, orig:JSON.parse(JSON.stringify(s)) };
          canvas.setPointerCapture(ev.pointerId);
        }
        redraw();
      });

      canvas.addEventListener('pointermove', (ev)=>{ const p = toLocal(ev);
        // update cursor when idle
        if(!drawing && (!current || (!current.move && !current.resize))){ const hit = hitTest(p); if(hit>=0){ const s=shapes[hit]; const handles = getHandlesForShape(s); let over=null; for(const h of handles){ if(p.x>=h.x-HALF_HANDLE && p.x<=h.x+HALF_HANDLE && p.y>=h.y-HALF_HANDLE && p.y<=h.y+HALF_HANDLE){ over=h.name; break; } } if(over){ canvas.style.cursor = (over==='nw' || over==='se') ? 'nwse-resize' : (over==='ne' || over==='sw') ? 'nesw-resize' : 'pointer'; } else { canvas.style.cursor = 'move'; } } else { canvas.style.cursor = (tool==='pen') ? 'crosshair' : 'default'; } }

        if(current && current.resize){ const s = shapes[current.shapeIndex]; const h = current.handle;
            if(s.type==='rect' || s.type==='circle' || s.type==='image'){
              // support shift to constrain aspect ratio
              if(h==='se'){ let nx = p.x - s.x; let ny = p.y - s.y; if(ev.shiftKey){ const sz = Math.max(Math.abs(nx), Math.abs(ny)); nx = sz * Math.sign(nx||1); ny = sz * Math.sign(ny||1); } s.w = nx; s.h = ny; }
              else if(h==='ne'){ let nx = p.x - s.x; let ny = (s.y + s.h) - p.y; if(ev.shiftKey){ const sz = Math.max(Math.abs(nx), Math.abs(ny)); nx = sz * Math.sign(nx||1); ny = sz * Math.sign(ny||1); } s.w = nx; s.h = (s.y + s.h) - p.y; s.y = p.y; }
              else if(h==='nw'){ let nx = (s.x + s.w) - p.x; let ny = (s.y + s.h) - p.y; if(ev.shiftKey){ const sz = Math.max(Math.abs(nx), Math.abs(ny)); nx = sz * Math.sign(nx||1); ny = sz * Math.sign(ny||1); } s.w = nx; s.h = ny; s.x = p.x; s.y = p.y; }
              else if(h==='sw'){ let nx = (s.x + s.w) - p.x; let ny = p.y - s.y; if(ev.shiftKey){ const sz = Math.max(Math.abs(nx), Math.abs(ny)); nx = sz * Math.sign(nx||1); ny = sz * Math.sign(ny||1); } s.w = nx; s.h = ny; s.x = p.x; }
            } else if(s.type==='line'){
              if(h==='p1'){ s.x1 = p.x; s.y1 = p.y; } else if(h==='p2'){ s.x2 = p.x; s.y2 = p.y; }
            }
            // normalize
            if(s.w!==undefined && s.w<0){ s.x += s.w; s.w = Math.abs(s.w); }
            if(s.h!==undefined && s.h<0){ s.y += s.h; s.h = Math.abs(s.h); }
            redraw(); return; }

        if(current && current.move){ const s = shapes[current.shapeIndex]; const dx = p.x - current.startPt.x; const dy = p.y - current.startPt.y;
          if(s.type==='rect' || s.type==='circle' || s.type==='image'){ s.x = current.orig.x + dx; s.y = current.orig.y + dy; }
          else if(s.type==='line'){ s.x1 = current.orig.x1 + dx; s.y1 = current.orig.y1 + dy; s.x2 = current.orig.x2 + dx; s.y2 = current.orig.y2 + dy; }
          else if(s.type==='pen'){ s.path = (current.orig.path||[]).map(pt=>({ x: pt.x + dx, y: pt.y + dy })); }
            redraw(); return; }

        if(!drawing) return; if(tool==='pen' && current){ const w = Math.max(1, (lineWidth || 2) * (p.pressure || 1)); current.path.push({ x: p.x, y: p.y, w }); redraw(); } else if((tool==='rect' || tool==='circle') && current){ current.w = p.x - current.x; current.h = p.y - current.y; redraw(); } else if(tool==='line' && current){ current.x2 = p.x; current.y2 = p.y; redraw(); }
      });

            canvas.addEventListener('pointerup', (ev)=>{ drawing=false; if(current){ if(current.resize){ saveShapes(); current=null; redraw(); canvas.releasePointerCapture(ev.pointerId); return; } if(current.move){ saveShapes(); current=null; redraw(); canvas.releasePointerCapture(ev.pointerId); return; }
              if(current.type==='pen'){ if(!current._isExisting){ shapes.push(current); } } else if(current.type==='rect' || current.type==='circle'){ if(current.w<0){ current.x+=current.w; current.w=Math.abs(current.w); } if(current.h<0){ current.y+=current.h; current.h=Math.abs(current.h); } shapes.push(current); } else if(current.type==='line'){ shapes.push(current); }
              current=null; redraw(); saveShapes(); try{ canvas.releasePointerCapture(ev.pointerId); }catch(e){} } });

      function saveShapes(){ localStorage.setItem('whiteboard:shapes', JSON.stringify(shapes)); }
      function loadShapes(){ try{ const data = localStorage.getItem('whiteboard:shapes'); if(data) shapes = JSON.parse(data).filter(s=>s && s.type && s.type!=='text'); }catch(e){ shapes=[]; } redraw(); }

      // enhance loadShapes to hydrate image objects
      (function(){ const _load = loadShapes; loadShapes = function(){ try{ const data = localStorage.getItem('whiteboard:shapes'); if(data) shapes = JSON.parse(data).filter(s=>s && s.type && s.type!=='text'); else shapes = []; // hydrate images
        shapes.forEach(s=>{ if(s.type==='image' && s.src && !s._img){ const img=new Image(); img.onload=()=>{ s._img = img; redraw(); }; img.src = s.src; } });
        }catch(e){ shapes=[]; } redraw(); }; })();

      clearBtn.addEventListener('click', ()=>{ if(confirm('Clear whiteboard?')){ pushHistory(); shapes=[]; saveShapes(); redraw(); }});
      const undoBtn = document.getElementById('wb-undo');
      if(undoBtn) undoBtn.addEventListener('click', ()=>{ undo(); });

      // bring to front / send to back
      const bringBtn = document.getElementById('wb-bring-front');
      const sendBtn = document.getElementById('wb-send-back');
      if(bringBtn) bringBtn.addEventListener('click', ()=>{ if(selected<0) return; const s = shapes.splice(selected,1)[0]; shapes.push(s); selected = shapes.length-1; saveShapes(); redraw(); });
      if(sendBtn) sendBtn.addEventListener('click', ()=>{ if(selected<0) return; const s = shapes.splice(selected,1)[0]; shapes.unshift(s); selected = 0; saveShapes(); redraw(); });

      const backBtn = document.getElementById('wb-back-free');
      if(backBtn) backBtn.addEventListener('click', ()=>{ setTool('pen'); });

      // removed Bezier checkbox — pen smoothing uses continuous line

      // keyboard: Ctrl/Cmd+Z for undo
      document.addEventListener('keydown', (e)=>{
        const z = e.key && (e.key.toLowerCase() === 'z');
        if(!z) return;
        if((e.ctrlKey || e.metaKey) && !e.shiftKey){ e.preventDefault(); undo(); }
      });
      saveBtn.addEventListener('click', async ()=>{
        // Ensure all image shapes have _img loaded before export
        const loads = [];
        shapes.forEach(s=>{ if(s.type==='image' && !s._img && s.src){ loads.push(new Promise((res)=>{ const img=new Image(); img.onload=()=>{ s._img = img; res(); }; img.onerror=()=>res(); img.src = s.src; })); } });
        if(loads.length) await Promise.all(loads);
        const tmp=document.createElement('canvas'); tmp.width=canvas.width; tmp.height=canvas.height; const tctx=tmp.getContext('2d'); tctx.setTransform(deviceRatio,0,0,deviceRatio,0,0); shapes.forEach(s=>drawTo(tctx,s)); const data = tmp.toDataURL('image/png'); const a=document.createElement('a'); a.href=data; a.download=`whiteboard-${Date.now()}.png`; a.click(); saveShapes();
      });

      function drawTo(c,s){ c.save(); c.strokeStyle=s.color; c.fillStyle=s.color; c.lineWidth=s.lineWidth||2; if(s.type==='pen'){ if(!s.path||s.path.length===0){ c.restore(); return; } // draw pen
          drawSmoothPath(c, s.path);
        } else if(s.type==='rect'){ if(s.fill) c.fillRect(s.x,s.y,s.w,s.h); c.strokeRect(s.x,s.y,s.w,s.h); } else if(s.type==='circle'){ const cx=s.x+s.w/2, cy=s.y+s.h/2, rx=Math.abs(s.w/2), ry=Math.abs(s.h/2); c.beginPath(); c.ellipse(cx,cy,rx,ry,0,0,Math.PI*2); if(s.fill) c.fill(); c.stroke(); } else if(s.type==='line'){ c.beginPath(); c.moveTo(s.x1, s.y1); c.lineTo(s.x2, s.y2); c.stroke(); } else if(s.type==='image'){ if(s._img){ try{ c.drawImage(s._img, s.x, s.y, s.w, s.h); }catch(e){ /* ignore */ } } else if(s.src){ // fallback: draw by creating an Image synchronously (may be async)
            const img = new Image(); img.onload = ()=>{ try{ c.drawImage(img, s.x, s.y, s.w, s.h); }catch(e){} }; img.src = s.src; }
        } c.restore(); }

      // image import handling
      const importBtn = document.getElementById('wb-import');
      const imgInput = document.getElementById('wb-image-input');
      if(importBtn && imgInput){ importBtn.addEventListener('click', ()=>imgInput.click()); imgInput.addEventListener('change', (ev)=>{
        const f = ev.target.files && ev.target.files[0]; if(!f) return; const reader = new FileReader(); reader.onload = (e)=>{
          const dataUrl = e.target.result;
          // if replaceImageIndex is set, replace that shape instead of adding a new one
          if(replaceImageIndex>=0 && shapes[replaceImageIndex] && shapes[replaceImageIndex].type==='image'){
            pushHistory(); const s = shapes[replaceImageIndex]; s.src = dataUrl; const img = new Image(); img.onload = ()=>{ s._img = img; saveShapes(); redraw(); };
            img.src = dataUrl; replaceImageIndex = -1; ev.target.value=''; return;
          }
          pushHistory(); const rect = canvas.getBoundingClientRect(); const defaultW = Math.min(300, rect.width*0.5); const defaultH = defaultW; const x = (rect.width - defaultW)/2; const y = (rect.height - defaultH)/2; const shape = { type:'image', x, y, w:defaultW, h:defaultH, src:dataUrl };
          const img = new Image(); img.onload = ()=>{ shape._img = img; redraw(); };
          img.src = dataUrl; shapes.push(shape); saveShapes(); redraw(); ev.target.value=''; };
        reader.readAsDataURL(f);
      }); }

      // double-click on image to replace it
      canvas.addEventListener('dblclick', (ev)=>{
        const p = toLocal(ev); const idx = hitTest(p);
        if(idx<0) return; const s = shapes[idx]; if(s.type==='image'){ replaceImageIndex = idx; imgInput.click(); }
      });

      closeBtn.addEventListener('click', ()=>{ wb.classList.remove('open'); wb.setAttribute('aria-hidden','true'); });
      const openWhiteboard = ()=>{ wb.classList.add('open'); wb.setAttribute('aria-hidden','false'); resize(); loadShapes(); const firstTool = tools['pen']; if(firstTool) firstTool.focus(); };
      window.addEventListener('resize', ()=>{ if(wb.classList.contains('open')) resize(); });
      document.addEventListener('keydown', (e)=>{ if(e.key==='w'){ if(wb.classList.contains('open')){ wb.classList.remove('open'); wb.setAttribute('aria-hidden','true'); } else { openWhiteboard(); } } });

      // initialize
      setTool('pen'); loadShapes();
    })();
  </script>
</body>
</html>