File size: 184,742 Bytes
ed1e1a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d2ab6c
ed1e1a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
// static/js/documentLibrary.js
/**
 * Document Library — modal with Chats / Documents / Research / Archive tabs.
 * Extracted from document.js to reduce file size.
 */

import { topPortalZ } from './toolWindowZOrder.js';
import uiModule from './ui.js';
import sessionModule from './sessions.js';
import spinnerModule from './spinner.js';
import markdownModule from './markdown.js';
import { makeWindowDraggable } from './windowDrag.js';
import { langIcon } from './langIcons.js';
import { registerMenuDismiss, dismissOrRemove } from './escMenuStack.js';

// ── Injected references from documentModule ──
let API_BASE = '';
let _esc;          // HTML-escape function
let _getDocs;      // () => Map of open docs
let _isOpenFn;     // () => boolean — is doc panel open
let _createDocument;
let _loadDocument;
let _switchToDoc;
let _openPanel;
let _addDocToTabs;
let _syncDocIndicator;

export function initLibrary(config) {
  API_BASE        = config.apiBase;
  _esc            = config.esc;
  _getDocs        = config.getDocs;
  _isOpenFn       = config.isOpen;
  _createDocument = config.createDocument;
  _loadDocument   = config.loadDocument;
  _switchToDoc    = config.switchToDoc;
  _openPanel      = config.openPanel;
  _addDocToTabs   = config.addDocToTabs;
  _syncDocIndicator = config.syncDocIndicator;
}

// ── Library state ──
let _libraryOpen = false;
// Track which tabs have already played their domino-in cascade so we only
// animate the *first* time content loads per page session — tab swaps and
// re-renders after that are instant.
const _libraryCascadedTabs = new Set();
function _maybeCascadeGrid(grid, tabKey) {
  if (!grid || !tabKey || _libraryCascadedTabs.has(tabKey)) return;
  _libraryCascadedTabs.add(tabKey);
  grid.classList.add('doclib-just-opened');
  setTimeout(() => grid.classList.remove('doclib-just-opened'), 900);
}
let _libraryDocs = [];
let _libraryTotal = 0;
let _libraryOffset = 0;
let _docsVisibleLimit = 20;  // chunked reveal (matches the Chats tab's 20)
let _libraryLanguages = {};
let _librarySessionCount = 0;
let _libraryActiveLanguage = null;
let _librarySort = 'recent';
let _librarySearch = '';
let _librarySearchDebounce = null;

// Highlight the active search terms inside a plain string. Escapes first,
// then wraps each whitespace-separated term in <mark>. Multi-term, matching
// the backend's per-term search, so every word that matched is marked.
function _hlSearch(text) {
  const esc = _esc(text || '');
  const q = (_librarySearch || '').trim();
  if (!q) return esc;
  const toks = [...new Set(q.split(/\s+/).filter(Boolean))]
    .sort((a, b) => b.length - a.length)             // prefer longer matches
    .map(t => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
  if (!toks.length) return esc;
  try {
    return esc.replace(new RegExp(`(${toks.join('|')})`, 'gi'),
                       '<mark class="doclib-search-hl">$1</mark>');
  } catch { return esc; }
}

function _safeResearchHref(raw) {
  try {
    const parsed = new URL(String(raw || '').trim(), window.location.origin);
    if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return _esc(parsed.href);
  } catch {}
  return '';
}

let _libraryEscHandler = null;
let _librarySelectMode = false;
let _librarySelectedIds = new Set();
let _libraryImportMode = false;
let _libScrollBound = false;   // infinite-scroll listener attached once
let _libraryArchivedView = false;   // Documents tab showing archived docs?

// ---- Library animation helpers ----

  /** Collapse an expanded card */
  function _collapseExpandedCard(card) {
    const grid = card.closest('.doclib-grid');
    const instant = card?.dataset?.spaceToggle === '1';
    card.classList.remove('doclib-card-expanded');
    // Release the height lock so grid returns to natural size
    if (grid) {
      grid.style.minHeight = '';
      grid.style.maxHeight = '';
    }
    const reader = card.querySelector('.doclib-card-reader');
    if (reader) reader.remove();

    // Fade siblings back in
    if (grid && !instant) {
      const siblings = [...grid.querySelectorAll('.doclib-card')].filter(c => c !== card);
      siblings.forEach(s => { s.style.opacity = '0'; });
      requestAnimationFrame(() => {
        siblings.forEach(s => {
          s.style.transition = 'opacity 0.15s ease';
          s.style.opacity = '1';
        });
        setTimeout(() => { siblings.forEach(s => { s.style.transition = ''; s.style.opacity = ''; }); }, 200);
      });
    }
  }

  // Fetch a chat's full history and serialize as plain-text transcript,
  // then write to the clipboard. Same User: / Assistant: format the chat
  // header's "Copy Chat" button uses, but works for any session ID — the
  // library doesn't need the chat to be loaded in the UI first.
  async function _copyChatById(sessionId) {
    try {
      const res = await fetch(`${API_BASE}/api/history/${sessionId}`, { credentials: 'same-origin' });
      if (!res.ok) throw new Error(res.statusText);
      const data = await res.json();
      const history = Array.isArray(data) ? data : (data.history || []);
      const lines = [];
      for (const m of history) {
        if (m.role !== 'user' && m.role !== 'assistant') continue;
        const label = m.role === 'user' ? 'User' : 'Assistant';
        const body = (m.content || '')
          .replace(/<think>[\s\S]*?<\/think>/g, '')
          .replace(/<think>[\s\S]*$/, '')
          .trim();
        if (body) lines.push(`${label}: ${body}`);
      }
      const text = lines.join('\n\n');
      if (uiModule && uiModule.copyToClipboard) {
        await uiModule.copyToClipboard(text);
      } else {
        await navigator.clipboard.writeText(text);
      }
    } catch (err) {
      if (uiModule && uiModule.showError) uiModule.showError('Failed to copy chat');
    }
  }

  // Long-press a list card to open its actions menu. `menuSelector` resolves
  // the existing ••• button on the card; on hold we trigger its click so the
  // dropdown opens in its usual spot. Moved finger >10px or release before
  // 500ms cancels.
  function _attachLongPressMenu(card, menuSelector) {
    let hold = null;
    let start = null;
    const cancel = () => { if (hold) { clearTimeout(hold); hold = null; } start = null; };
    card.addEventListener('pointerdown', (e) => {
      if (e.target.closest(menuSelector + ', .memory-select-cb, button')) return;
      start = { x: e.clientX, y: e.clientY };
      hold = setTimeout(() => {
        hold = null;
        card._suppressNextClick = true;
        setTimeout(() => { card._suppressNextClick = false; }, 400);
        if (navigator.vibrate) try { navigator.vibrate(15); } catch {}
        const btn = card.querySelector(menuSelector);
        if (btn) btn.click();
      }, 500);
    });
    card.addEventListener('pointermove', (e) => {
      if (!start) return;
      if (Math.hypot(e.clientX - start.x, e.clientY - start.y) > 10) cancel();
    });
    card.addEventListener('pointerup', cancel);
    card.addEventListener('pointercancel', cancel);
  }

  // Inline icons used by the chats/archive/research dropdown rows. Match the
  // ones used by the documents-tab card menu so the visual language stays
  // consistent across tabs.
  const _LIB_DD_ICONS = {
    open: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',
    archive: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>',
    restore: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9"/><polyline points="3 4 3 9 8 9"/></svg>',
    delete: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>',
    clone: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',
    copy: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>',
  };

  function _showLibDropdown(anchor, items, opts) {
    opts = opts || {};
    document.querySelectorAll('._lib-dd').forEach(dismissOrRemove);
    const dd = document.createElement('div');
    dd.className = 'dropdown session-dropdown-menu _lib-dd';
    for (const item of items) {
      const row = document.createElement('div');
      row.className = 'dropdown-item-compact' + (item.danger ? ' dropdown-item-danger' : '');
      const iconKey = item.icon || item.label.toLowerCase();
      const iconSvg = _LIB_DD_ICONS[iconKey] || '';
      row.innerHTML = (iconSvg ? '<span class="dropdown-icon">' + iconSvg + '</span>' : '') + '<span>' + item.label + '</span>';
      row.addEventListener('click', (e) => { e.stopPropagation(); teardown(); item.action(); });
      dd.appendChild(row);
    }
    if (typeof opts.onSelect === 'function') {
      const sel = document.createElement('div');
      sel.className = 'dropdown-item-compact';
      sel.innerHTML =
        '<span class="dropdown-icon"><span style="font-size:16px;line-height:1;position:relative;top:-2px;">●</span></span>'
        + '<span>Select</span>';
      sel.addEventListener('click', (e) => { e.stopPropagation(); teardown(); opts.onSelect(); });
      dd.appendChild(sel);
    }
    const cancel = document.createElement('div');
    cancel.className = 'dropdown-item-compact dropdown-cancel-mobile';
    cancel.innerHTML =
      '<span class="dropdown-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></span>'
      + '<span>Cancel</span>';
    cancel.addEventListener('click', (e) => { e.stopPropagation(); teardown(); if (typeof opts.onCancel === 'function') opts.onCancel(); });
    dd.appendChild(cancel);
    document.body.appendChild(dd);
    const rect = anchor.getBoundingClientRect();
    dd.style.right = (window.innerWidth - rect.right) + 'px';
    dd.style.top = (rect.bottom + 2) + 'px';
    dd.style.display = 'block';
    dd.style.zIndex = String(topPortalZ());
    requestAnimationFrame(() => {
      const mr = dd.getBoundingClientRect();
      if (mr.bottom > window.innerHeight - 8) {
        dd.style.top = (rect.top - mr.height - 2) + 'px';
      }
      if (mr.left < 8) { dd.style.left = '8px'; dd.style.right = 'auto'; }
    });
    // Single idempotent teardown shared by every dismissal path (item click,
    // outside click, swipe, and the Escape arbiter via registerMenuDismiss).
    let _unreg = () => {};
    const teardown = () => {
      _unreg(); _unreg = () => {};
      document.removeEventListener('click', close);
      dd.remove();
    };
    const close = (e) => { if (!dd.contains(e.target)) teardown(); };
    setTimeout(() => document.addEventListener('click', close), 0);
    _unreg = registerMenuDismiss(teardown);
    dd._dismiss = teardown;   // let bulk removers (reopen sweep) tear down cleanly

    // Swipe-down-to-dismiss (mobile). Mirrors the bottom-sheet feel — drag the
    // popup down and release past the threshold to close. Below threshold,
    // snap back. Vertical-only; horizontal flicks fall through to scrolling.
    let _swipeStart = null;
    let _swipeDy = 0;
    dd.addEventListener('touchstart', (e) => {
      if (e.touches.length !== 1) return;
      _swipeStart = { x: e.touches[0].clientX, y: e.touches[0].clientY };
      _swipeDy = 0;
      dd.style.transition = '';
    }, { passive: true });
    dd.addEventListener('touchmove', (e) => {
      if (!_swipeStart || e.touches.length !== 1) return;
      const dx = e.touches[0].clientX - _swipeStart.x;
      const dy = e.touches[0].clientY - _swipeStart.y;
      if (Math.abs(dy) < Math.abs(dx)) { _swipeStart = null; return; }
      if (dy > 0) {
        _swipeDy = dy;
        dd.style.transform = 'translateY(' + dy + 'px)';
        dd.style.opacity = String(Math.max(0.3, 1 - dy / 240));
      }
    }, { passive: true });
    dd.addEventListener('touchend', () => {
      if (!_swipeStart) return;
      _swipeStart = null;
      if (_swipeDy > 60) {
        dd.style.transition = 'transform 0.15s ease, opacity 0.15s ease';
        dd.style.transform = 'translateY(120px)';
        dd.style.opacity = '0';
        // Unregister + drop the outside-click listener now; defer the DOM
        // removal so the slide-out animation can play.
        _unreg(); _unreg = () => {};
        document.removeEventListener('click', close);
        setTimeout(() => dd.remove(), 160);
      } else {
        dd.style.transition = 'transform 0.18s ease, opacity 0.18s ease';
        dd.style.transform = '';
        dd.style.opacity = '';
      }
    });
  }

  // ---- Document Library ----

  function libraryRelativeTime(isoString) {
    if (!isoString) return '';
    const now = Date.now();
    const then = new Date(isoString).getTime();
    const diffS = Math.floor((now - then) / 1000);
    if (diffS < 60) return 'just now';
    const diffM = Math.floor(diffS / 60);
    if (diffM < 60) return diffM + 'm ago';
    const diffH = Math.floor(diffM / 60);
    if (diffH < 24) return diffH + 'h ago';
    const diffD = Math.floor(diffH / 24);
    if (diffD === 1) return 'yesterday';
    if (diffD < 14) return diffD + 'd ago';
    const diffW = Math.floor(diffD / 7);
    if (diffW < 8) return diffW + 'w ago';
    return new Date(isoString).toLocaleDateString();
  }

  async function libraryFetch(append) {
    if (!append) _libraryOffset = 0;
    // Bump page size to the backend max (50) so fullscreen doesn't leave
    // empty space below the loaded rows — same idea as emailLibrary's
    // limit=100, but documents_library validates `le=50` so we have to
    // cap at that. Auto-fill loop below picks up any remaining gap.
    const params = new URLSearchParams({
      sort: _librarySort,
      offset: String(_libraryOffset),
      limit: '50',
    });
    if (_librarySearch) params.set('search', _librarySearch);
    if (_libraryActiveLanguage) params.set('language', _libraryActiveLanguage);
    if (_libraryArchivedView) params.set('archived', 'true');

    try {
      const res = await fetch(`${API_BASE}/api/documents/library?${params}`);
      if (!res.ok) throw new Error(res.statusText);
      const data = await res.json();

      if (append) {
        _libraryDocs = _libraryDocs.concat(data.documents);
      } else {
        _libraryDocs = data.documents;
        _docsVisibleLimit = 20;  // reset chunk on a fresh load / search / sort
      }
      _libraryTotal = data.total;
      _libraryLanguages = data.languages;
      _librarySessionCount = data.session_count;

      libraryRenderStats();
      libraryRenderLangChips();
      libraryRenderGrid();
      libraryRenderLoadMore();
    } catch (e) {
      console.error('Library fetch error:', e);
    }
  }

  function libraryRenderStats() {
    const el = document.getElementById('doclib-stats');
    if (!el) return;
    const totalAll = Object.values(_libraryLanguages).reduce((a, b) => a + b, 0);
    if (_librarySearch || _libraryActiveLanguage) {
      el.textContent = `${_libraryTotal} of ${totalAll} document${totalAll !== 1 ? 's' : ''}`;
    } else {
      el.textContent = `${totalAll} document${totalAll !== 1 ? 's' : ''}`;
    }
  }

  function libraryRenderLangChips() {
    const wrap = document.getElementById('doclib-chips');
    if (!wrap) return;
    // Remove only language chip buttons, keep sort/select elements
    wrap.querySelectorAll('.memory-cat-chip').forEach(c => c.remove());
    const totalAll = Object.values(_libraryLanguages).reduce((a, b) => a + b, 0);

    // Hide the "all (0)" chip + lang chips entirely when there are no docs.
    if (totalAll === 0) return;

    const allChip = document.createElement('button');
    allChip.className = 'memory-cat-chip' + (!_libraryActiveLanguage ? ' active' : '');
    allChip.textContent = `all (${totalAll})`;
    allChip.addEventListener('click', () => {
      if (_librarySelectMode) {
        _libraryDocs.forEach(d => _librarySelectedIds.add(d.id));
        libraryUpdateBulkCount();
        const selectAllEl = document.getElementById('doclib-select-all');
        if (selectAllEl) selectAllEl.checked = true;
        libraryRenderGrid();
        return;
      }
      _libraryActiveLanguage = null;
      libraryFetch(false);
    });
    wrap.appendChild(allChip);

    const sorted = Object.entries(_libraryLanguages).sort((a, b) => b[1] - a[1]);
    for (const [lang, count] of sorted) {
      const chip = document.createElement('button');
      chip.className = 'memory-cat-chip' + (_libraryActiveLanguage === lang ? ' active' : '');
      chip.textContent = `${lang} (${count})`;
      chip.addEventListener('click', () => {
        _libraryActiveLanguage = lang;
        libraryFetch(false);
      });
      wrap.appendChild(chip);
    }
  }

  function libraryRemoveDocumentFromState(docId) {
    const removed = _libraryDocs.find(d => String(d.id) === String(docId));
    _libraryDocs = _libraryDocs.filter(d => String(d.id) !== String(docId));
    _librarySelectedIds.delete(docId);
    _libraryTotal = Math.max(0, _libraryTotal - 1);

    const lang = removed && (removed.language || 'text');
    if (lang && Object.prototype.hasOwnProperty.call(_libraryLanguages, lang)) {
      const next = Math.max(0, Number(_libraryLanguages[lang] || 0) - 1);
      if (next > 0) {
        _libraryLanguages[lang] = next;
      } else {
        delete _libraryLanguages[lang];
      }
    }

    libraryRenderStats();
    libraryRenderLangChips();
    libraryUpdateBulkCount();
  }

  function libraryRenderGrid() {
    const grid = document.getElementById('doclib-grid');
    if (!grid) return;
    // An open card menu is mounted on <body> (to escape overflow clipping), so
    // clearing the grid would orphan it; dismiss it first so its listener +
    // Escape-stack entry go too.
    document.querySelectorAll('.doclib-card-dropdown').forEach(dismissOrRemove);
    grid.innerHTML = '';
    // Drop any previous inline load-more — regenerated below alongside the list.
    if (grid.parentElement) grid.parentElement.querySelectorAll(':scope > .doclib-inline-load-more').forEach(b => b.remove());

    if (_libraryDocs.length === 0) {
      if (_librarySearch || _libraryActiveLanguage) {
        grid.innerHTML = '<div class="doclib-empty">No documents match your search.</div>';
      } else {
        const _impIco = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin:0 4px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>';
        grid.innerHTML =
          '<div class="doclib-empty" style="display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap;">' +
            '<span>No documents yet</span>' +
            '<span style="opacity:0.7;font-size:11px;">' +
              '<a href="#" data-doclib-import style="color:var(--accent,var(--red));text-decoration:underline;">Import' + _impIco + '</a>' +
              ' &middot; or create one in a session' +
            '</span>' +
          '</div>';
        grid.querySelector('[data-doclib-import]')?.addEventListener('click', (e) => {
          e.preventDefault();
          document.getElementById('doclib-import-file-btn')?.click();
        });
      }
      return;
    }
    _maybeCascadeGrid(grid, 'documents');

    // Reveal in 20-at-a-time chunks (matches the Chats tab). The legacy
    // server-pagination button is suppressed in libraryRenderLoadMore; this
    // inline button is the single control.
    const shown = _libraryDocs.slice(0, _docsVisibleLimit);
    for (const doc of shown) {
      grid.appendChild(libraryCreateCard(doc));
    }
    // Show a "Load more" while either more loaded docs remain to reveal, or
    // more exist on the server beyond what we've fetched.
    const shownCount = shown.length;
    if (shownCount < _libraryTotal) {
      const btn = document.createElement('button');
      btn.className = 'doclib-load-more doclib-inline-load-more';
      btn.id = 'doclib-docs-load-more';
      btn.textContent = `Load more (${shownCount} of ${_libraryTotal})`;
      btn.addEventListener('click', async () => {
        _docsVisibleLimit += 20;
        // Need more than we've fetched? pull the next server page first.
        if (_docsVisibleLimit > _libraryDocs.length && _libraryDocs.length < _libraryTotal) {
          _libraryOffset = _libraryDocs.length;
          await libraryFetch(true);  // appends + re-renders
        } else {
          libraryRenderGrid();
        }
      });
      grid.parentElement.appendChild(btn);
    }
  }

  // Infinite scroll for the library (mobile + desktop), covering EVERY tab —
  // Documents, Chats, Research, Archive all render a `.doclib-inline-load-more`
  // button (regenerated fresh each render). A capture-phase scroll listener
  // catches whichever element actually scrolls and, when the visible button
  // nears the viewport bottom, clicks it — reusing each tab's own load logic.
  // We mark a button once clicked so the SAME instance can't double-fire (the
  // next render makes a fresh, unmarked one), which is safe for both the sync
  // reveal tabs (Chats/Research) and the async fetch tabs (Documents/Archive).
  if (!_libScrollBound) {
    _libScrollBound = true;
    let _tick = false;
    const _maybeAutoLoad = () => {
      _tick = false;
      if (!_libraryOpen) return;
      for (const btn of document.querySelectorAll('.doclib-inline-load-more')) {
        if (btn.dataset.autoLoaded) continue;
        if (!btn.offsetParent) continue;   // inactive tab (hidden)
        if (btn.getBoundingClientRect().top > window.innerHeight + 600) continue;
        btn.dataset.autoLoaded = '1';
        btn.click();
        break;   // one load per scroll tick
      }
    };
    document.addEventListener('scroll', () => {
      if (_tick) return;
      _tick = true;
      requestAnimationFrame(_maybeAutoLoad);
    }, true);
  }

  function libraryCreateCard(doc) {
    const card = document.createElement('div');
    card.className = 'doclib-card memory-item';
    card.dataset.docId = doc.id;
    if (_librarySelectMode && _librarySelectedIds.has(doc.id)) {
      card.classList.add('selected');
    }

    // Checkbox for select mode
    if (_librarySelectMode) {
      const cb = document.createElement('input');
      cb.type = 'checkbox';
      cb.className = 'memory-select-cb';
      cb.checked = _librarySelectedIds.has(doc.id);
      cb.addEventListener('click', (e) => e.stopPropagation());
      cb.addEventListener('change', () => {
        libraryToggleSelectItem(doc.id);
        card.classList.toggle('selected', _librarySelectedIds.has(doc.id));
        const selectAllEl = document.getElementById('doclib-select-all');
        if (selectAllEl) selectAllEl.checked = _libraryDocs.every(d => _librarySelectedIds.has(d.id));
      });
      card.appendChild(cb);
    }

    // Content wrapper
    const content = document.createElement('div');
    content.style.cssText = 'flex:1;min-width:0;padding-top:4px;';

    // Title row with version badge
    const titleRow = document.createElement('div');
    titleRow.style.cssText = 'display:flex;align-items:center;gap:6px;width:100%;';
    const titleEl = document.createElement('span');
    titleEl.className = 'memory-item-title';
    titleEl.style.cssText = 'flex:0 1 auto;min-width:0;';
    // Language-specific icon next to the title (matches the document's type:
    // markdown/csv/python/html/etc.). Falls back to the generic document icon
    // when the language has no dedicated glyph.
    const _GEN_DOC_ICON = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.4;flex-shrink:0;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>';
    const _langSvg = doc.language && doc.language !== 'text'
      ? langIcon(doc.language, 12, { style: 'vertical-align:-2px;margin-right:4px;opacity:0.55;flex-shrink:0;color:currentColor;' })
      : '';
    titleEl.innerHTML = (_langSvg || _GEN_DOC_ICON) + _hlSearch(doc.title || 'Untitled');
    titleRow.appendChild(titleEl);
    const verBadge = document.createElement('span');
    verBadge.style.cssText = 'font-size:9px;padding:1px 6px;border-radius:8px;background:color-mix(in srgb, var(--red) 15%, transparent);border:1px solid color-mix(in srgb, var(--red) 40%, transparent);color:var(--red);flex-shrink:0;';
    verBadge.textContent = 'v' + (doc.version_count || 1);
    titleRow.appendChild(verBadge);
    // Chevron pushed to the right end of the title row — collapsed
    // shows nothing, expanded reveals a downward chevron so the user
    // sees the card is open and can tap to close it.
    const chevron = document.createElement('span');
    chevron.className = 'doclib-card-chevron';
    chevron.style.marginLeft = 'auto';
    chevron.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg>';
    titleRow.appendChild(chevron);
    content.appendChild(titleRow);

    // Meta line: session → [lang-icon language] → time
    const meta = document.createElement('div');
    meta.className = 'memory-item-meta';
    meta.style.cssText = 'font-size:10px;opacity:0.55;margin-top:2px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;';
    const _esc = (s) => uiModule.esc(String(s || ''));
    const pieces = [];
    if (doc.session_name) pieces.push(`<span>${_esc(doc.session_name)}</span>`);
    if (doc.language && doc.language !== 'text') {
      // Per-language icon lives in the title row above; just the language
      // name here keeps the meta line scannable without duplicating the icon.
      pieces.push(`<span>${_esc(doc.language)}</span>`);
    }
    pieces.push(`<span>${_esc(libraryRelativeTime(doc.updated_at))}</span>`);
    meta.innerHTML = pieces.join('<span style="opacity:0.5;">\u00b7</span>');
    content.appendChild(meta);
    card.appendChild(content);

    // Header element (kept for expand/preview compatibility)
    const header = document.createElement('div');
    header.className = 'doclib-card-header';
    header.style.display = 'none';

    // Action buttons — "..." menu
    const actionsWrap = document.createElement('div');
    actionsWrap.className = 'memory-item-actions';
    const menuWrap = document.createElement('span');
    menuWrap.className = 'doclib-card-menu-wrap';
    menuWrap.style.position = 'relative';
    const menuBtn = document.createElement('button');
    menuBtn.className = 'memory-item-btn';
    menuBtn.title = 'Actions';
    menuBtn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg>';
    menuBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      // Mobile: the custom 5-item dropdown is too crowded — route through the
      // shared _showLibDropdown with a small set (Open, Clone) plus Select +
      // Cancel. Heavier actions (Archive, Delete, Export) live in bulk mode.
      if (window.innerWidth <= 768) {
        const items = [];
        if (doc.session_id) items.push({ label: 'Open', action: () => libraryOpenInSession(doc) });
        items.push({ label: 'Clone', action: () => libraryImportDocument(doc) });
        _showLibDropdown(menuBtn, items, { onSelect: () => {
          libraryEnterSelectMode();
          _librarySelectedIds.add(doc.id);
          libraryUpdateBulkCount();
          libraryRenderGrid();
        } });
        return;
      }
      const dropdown = menuWrap.querySelector('.doclib-card-dropdown') || document.body.querySelector('.doclib-card-dropdown[data-owner="' + CSS.escape(doc.id) + '"]');
      if (dropdown) {
        const isOpen = dropdown.style.display !== 'none' && dropdown.parentElement === document.body;
        if (isOpen) {
          hideCardDropdown();
        } else {
          // Position fixed on body to escape overflow clipping
          const rect = menuBtn.getBoundingClientRect();
          document.body.appendChild(dropdown);
          dropdown.dataset.owner = doc.id;
          dropdown.style.cssText = `position:fixed;z-index:${topPortalZ()};min-width:0;width:max-content;padding:4px;background:var(--panel);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.3);backdrop-filter:blur(12px);font-size:12px;display:block;`;
          dropdown.style.top = (rect.bottom + 4) + 'px';
          dropdown.style.left = 'auto';
          dropdown.style.right = (window.innerWidth - rect.right) + 'px';
          // Clamp to viewport
          requestAnimationFrame(() => {
            const mr = dropdown.getBoundingClientRect();
            if (mr.bottom > window.innerHeight - 8) dropdown.style.top = (rect.top - mr.height - 4) + 'px';
            if (mr.left < 8) { dropdown.style.left = '8px'; dropdown.style.right = 'auto'; }
          });
          // Close on outside click or Escape (the latter via the registry).
          _cardDocClick = (ev) => {
            if (!dropdown.contains(ev.target) && !menuWrap.contains(ev.target)) hideCardDropdown();
          };
          setTimeout(() => document.addEventListener('click', _cardDocClick, true), 0);
          _cardUnreg = registerMenuDismiss(hideCardDropdown);
        }
      }
    });
    menuWrap.appendChild(menuBtn);

    // Dropdown menu
    const dropdown = document.createElement('div');
    dropdown.className = 'doclib-card-dropdown';
    dropdown.style.cssText = 'display:none;position:absolute;top:100%;right:0;z-index:1000;min-width:0;width:max-content;padding:4px;background:var(--panel);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,0.3);backdrop-filter:blur(12px);font-size:12px;';

    // Single close path for the card action dropdown, shared by the toggle
    // button, the outside-click listener, every menu item, and the Escape
    // arbiter (via registerMenuDismiss). Hides the menu, returns it to its
    // wrapper, drops the outside-click listener, and unregisters from the
    // Escape stack. Idempotent — safe to call from whichever path fires first.
    let _cardUnreg = () => {};
    let _cardDocClick = null;
    function hideCardDropdown() {
      _cardUnreg(); _cardUnreg = () => {};
      if (_cardDocClick) { document.removeEventListener('click', _cardDocClick, true); _cardDocClick = null; }
      dropdown.style.display = 'none';
      if (dropdown.parentElement === document.body) menuWrap.appendChild(dropdown);
    }
    dropdown._dismiss = hideCardDropdown;   // bulk removers tear down through this

    const _di = (svg) => `<span class="dropdown-icon">${svg}</span>`;
    const _openIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>';

    // Open
    const openItem = document.createElement('button');
    openItem.className = 'dropdown-item-compact';
    openItem.style.cssText = 'background:none;border:none;width:100%;';
    openItem.innerHTML = _di(_openIco) + '<span>Open</span>';
    if (doc.session_id) {
      openItem.addEventListener('click', (e) => { e.stopPropagation(); hideCardDropdown(); libraryOpenInSession(doc); });
    } else {
      // Orphaned doc (closed / session detached) is still openable in the editor
      // by id — libraryOpenDocument handles the no-session case (#1602).
      openItem.title = 'Open in the editor';
      openItem.addEventListener('click', (e) => { e.stopPropagation(); hideCardDropdown(); libraryOpenDocument(doc); });
    }
    dropdown.appendChild(openItem);

    // Clone
    const _cloneIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
    const cloneItem = document.createElement('button');
    cloneItem.className = 'dropdown-item-compact';
    cloneItem.style.cssText = 'background:none;border:none;width:100%;';
    cloneItem.innerHTML = _di(_cloneIco) + '<span>Clone</span>';
    cloneItem.title = 'Clone to active session';
    cloneItem.addEventListener('click', (e) => { e.stopPropagation(); hideCardDropdown(); libraryImportDocument(doc); });
    dropdown.appendChild(cloneItem);

    // Export
    const _exportIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
    const exportItem = document.createElement('button');
    exportItem.className = 'dropdown-item-compact';
    exportItem.style.cssText = 'background:none;border:none;width:100%;';
    exportItem.innerHTML = _di(_exportIco) + '<span>Export</span>';
    exportItem.addEventListener('click', async (e) => {
      e.stopPropagation();
      hideCardDropdown();
      try {
        const res = await fetch(`${API_BASE}/api/document/${doc.id}`);
        if (!res.ok) throw new Error('Failed');
        const full = await res.json();
        const extMap = { javascript: '.js', python: '.py', html: '.html', css: '.css', markdown: '.md', json: '.json', yaml: '.yml', bash: '.sh', sql: '.sql', rust: '.rs', go: '.go', java: '.java', c: '.c', cpp: '.cpp', typescript: '.ts', ruby: '.rb', php: '.php', xml: '.xml', toml: '.toml', ini: '.ini' };
        const ext = extMap[full.language] || '.txt';
        const blob = new Blob([full.current_content || ''], { type: 'text/plain' });
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = (full.title || 'document') + ext;
        a.click();
        URL.revokeObjectURL(a.href);
      } catch { if (uiModule) uiModule.showError('Failed to export document'); }
    });
    dropdown.appendChild(exportItem);

    // Archive / Restore — soft-archive a doc out of the main list, or bring it back.
    const _archiveIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>';
    const archiveItem = document.createElement('button');
    archiveItem.className = 'dropdown-item-compact';
    archiveItem.style.cssText = 'background:none;border:none;width:100%;';
    archiveItem.innerHTML = _di(_archiveIco) + `<span>${_libraryArchivedView ? 'Restore' : 'Archive'}</span>`;
    archiveItem.title = _libraryArchivedView ? 'Restore to active documents' : 'Archive (hide from the main list)';
    archiveItem.addEventListener('click', async (e) => {
      e.stopPropagation();
      hideCardDropdown();
      const toArchived = !_libraryArchivedView;
      try {
        const res = await fetch(`${API_BASE}/api/document/${doc.id}/archive?archived=${toArchived}`, { method: 'POST', credentials: 'same-origin' });
        if (!res.ok) throw new Error('failed');
        // Drop it from the current view (it no longer belongs here) and refresh.
        libraryRemoveDocumentFromState(doc.id);
        libraryRenderGrid();
        if (uiModule) uiModule.showToast(toArchived ? 'Archived' : 'Restored');
      } catch { if (uiModule) uiModule.showError('Failed to ' + (toArchived ? 'archive' : 'restore')); }
    });
    dropdown.appendChild(archiveItem);

    // Delete
    const _deleteIco = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>';
    const deleteItem = document.createElement('button');
    deleteItem.className = 'dropdown-item-compact dropdown-item-danger';
    deleteItem.style.cssText = 'background:none;border:none;width:100%;';
    deleteItem.innerHTML = _di(_deleteIco) + '<span>Delete</span>';
    deleteItem.addEventListener('click', (e) => { e.stopPropagation(); hideCardDropdown(); libraryDeleteSingle(doc.id, card); });
    dropdown.appendChild(deleteItem);

    menuWrap.appendChild(dropdown);
    actionsWrap.appendChild(menuWrap);
    card.appendChild(actionsWrap);

    // Hidden header for expand/preview compatibility
    card.appendChild(header);

    // Inject library card hover styles once
    if (!document.getElementById('doclib-card-styles')) {
      const s = document.createElement('style');
      s.id = 'doclib-card-styles';
      s.textContent = `.doclib-card:hover .doclib-card-icon-btn{opacity:.4}.doclib-card-icon-btn:hover{opacity:1!important}.doclib-card-text-btn{background:none;border:1px solid var(--border);color:var(--fg-muted);font-size:10px;padding:3px 8px;border-radius:4px;cursor:pointer;transition:border-color .15s,color .15s}.doclib-card-text-btn:hover{border-color:var(--accent,var(--red));color:var(--accent,var(--red))}.doclib-card-text-btn-danger{border-color:var(--color-danger,#e06c75)!important;color:var(--color-danger,#e06c75)!important}.doclib-card-text-btn-danger:hover{border-color:#ff4d4d!important;color:#ff4d4d!important}.doclib-card-chevron{display:none;align-items:center;justify-content:center;align-self:center;opacity:0.6;transition:transform .15s ease;flex-shrink:0;height:14px;line-height:0}.doclib-card-expanded .doclib-card-chevron{display:inline-flex;transform:rotate(180deg)}.doclib-card-chevron svg{display:block}`;
      document.head.appendChild(s);
    }

    // Preview — hidden by default, shown on expand
    const preview = document.createElement('div');
    preview.className = 'doclib-card-preview';
    const pre = document.createElement('pre');
    const code = document.createElement('code');
    try {
      if (doc.language && doc.language !== 'text' && window.hljs && !_librarySearch) {
        code.innerHTML = window.hljs.highlight(doc.preview || '', { language: doc.language }).value;
      } else if (_librarySearch) {
        // While searching, highlight matched terms in the preview (plain
        // text) rather than syntax-highlighting — the match is what matters.
        code.innerHTML = _hlSearch(doc.preview || '');
      } else {
        code.textContent = doc.preview || '';
      }
    } catch {
      code.textContent = doc.preview || '';
    }
    pre.appendChild(code);
    preview.appendChild(pre);

    // Expanded-only action bar — inside preview
    const expandedActions = document.createElement('div');
    expandedActions.className = 'doclib-card-expanded-actions';

    const openBtn = document.createElement('button');
    openBtn.className = 'doclib-card-text-btn doclib-card-action-btn';
    openBtn.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><path d="M5 12h14M13 5l7 7-7 7"/></svg>Open';
    if (doc.session_id) {
      openBtn.title = 'Open in original session';
      openBtn.addEventListener('click', (e) => { e.stopPropagation(); libraryOpenInSession(doc); });
    } else {
      // Orphaned doc (closed / session detached) is still openable in the editor
      // by id — libraryOpenDocument handles the no-session case (#1602).
      openBtn.title = 'Open in the editor';
      openBtn.addEventListener('click', (e) => { e.stopPropagation(); libraryOpenDocument(doc); });
    }

    const cloneBtn = document.createElement('button');
    cloneBtn.className = 'doclib-card-text-btn doclib-card-action-btn';
    cloneBtn.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>Clone';
    cloneBtn.title = 'Clone — copy to active session';
    cloneBtn.addEventListener('click', (e) => { e.stopPropagation(); libraryImportDocument(doc); });

    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'doclib-card-text-btn doclib-card-action-btn doclib-card-text-btn-danger';
    deleteBtn.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>Delete';
    deleteBtn.addEventListener('click', (e) => { e.stopPropagation(); libraryDeleteSingle(doc.id, card); });

    // Archive sits next to Delete on the LEFT — same lineup as the chat
    // and research footers. Label flips to Restore inside the Archive view.
    const archiveBtn = document.createElement('button');
    archiveBtn.className = 'doclib-card-text-btn doclib-card-action-btn';
    archiveBtn.innerHTML = '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>' + (_libraryArchivedView ? 'Restore' : 'Archive');
    archiveBtn.title = _libraryArchivedView ? 'Restore to active documents' : 'Archive (hide from the main list)';
    archiveBtn.addEventListener('click', async (e) => {
      e.stopPropagation();
      const toArchived = !_libraryArchivedView;
      try {
        const res = await fetch(`${API_BASE}/api/document/${doc.id}/archive?archived=${toArchived}`, { method: 'POST', credentials: 'same-origin' });
        if (!res.ok) throw new Error('failed');
        libraryRemoveDocumentFromState(doc.id);
        libraryRenderGrid();
        if (uiModule) uiModule.showToast(toArchived ? 'Archived' : 'Restored');
      } catch { if (uiModule) uiModule.showError('Failed to ' + (toArchived ? 'archive' : 'restore')); }
    });

    const leftGroup = document.createElement('div');
    leftGroup.className = 'doclib-action-group';
    const btnRow = document.createElement('div');
    btnRow.className = 'doclib-action-btn-row';
    // Export lives in the ⋮ menu — keep the footer uncrowded with Clone + Open.
    btnRow.appendChild(cloneBtn);
    btnRow.appendChild(openBtn);
    leftGroup.appendChild(btnRow);
    // Delete furthest LEFT, then Archive; Open/Clone group on the RIGHT.
    // Nudge the Delete/Archive pair 8px left for alignment.
    deleteBtn.style.cssText += ';position:relative;left:-8px;';
    archiveBtn.style.cssText += ';position:relative;left:-8px;';
    expandedActions.appendChild(deleteBtn);
    expandedActions.appendChild(archiveBtn);
    expandedActions.appendChild(leftGroup);

    preview.appendChild(expandedActions);
    card.appendChild(preview);

    card.addEventListener('click', () => {
      if (card._suppressNextClick) { card._suppressNextClick = false; return; }
      if (_librarySelectMode) {
        const cb = card.querySelector('.memory-select-cb');
        if (cb) { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); }
      } else {
        libraryExpandCard(card, doc);
      }
    });
    _attachLongPressMenu(card, '.memory-item-btn');
    return card;
  }

  async function libraryExpandCard(card, doc) {
    const grid = card.closest('.doclib-grid');
    const instant = card?.dataset?.spaceToggle === '1';

    // Already expanded — collapse
    if (card.classList.contains('doclib-card-expanded')) {
      _collapseExpandedCard(card);
      return;
    }

    // Collapse any other expanded card
    if (grid) {
      grid.querySelectorAll('.doclib-card-expanded').forEach(c => _collapseExpandedCard(c));
    }

    // Fade siblings out before the CSS display:none kicks in
    const siblings = grid ? [...grid.querySelectorAll('.doclib-card')].filter(c => c !== card) : [];
    // Force explicit starting opacity so the first transition works
    siblings.forEach(s => { s.style.opacity = '1'; });
    // Force reflow so the browser registers the starting value
    if (!instant) {
      if (siblings.length) siblings[0].offsetHeight;
      siblings.forEach(s => { s.style.transition = 'opacity 0.12s ease'; s.style.opacity = '0'; });
    }

    // Capture the full grid + toolbar height so the modal stays the same
    // size on desktop. On mobile the modal is full-height and we want the
    // grid to claim all available space — skip the lock there.
    const isMobile = window.innerWidth <= 768;
    const toolbar = grid ? grid.closest('.admin-card')?.querySelector('.memory-toolbar') : null;
    const toolbarH = toolbar ? toolbar.offsetHeight : 0;
    if (grid && !isMobile) {
      grid.style.minHeight = (grid.offsetHeight + toolbarH) + 'px';
      grid.style.maxHeight = (grid.offsetHeight + toolbarH) + 'px';
    }

    // Wait for fade-out, then expand
    if (!instant) await new Promise(r => setTimeout(r, 120));

    card.classList.add('doclib-card-expanded');
    if (grid) grid.scrollTop = 0;

    // Clean up sibling inline styles (CSS display:none takes over now)
    siblings.forEach(s => { s.style.transition = ''; s.style.opacity = ''; });

    // Load full content into preview area
    const preview = card.querySelector('.doclib-card-preview');
    if (!preview) return;

    const actionsBar = preview.querySelector('.doclib-card-expanded-actions');
    const existingPre = preview.querySelector('pre');

    try {
      const res = await fetch(`${API_BASE}/api/document/${doc.id}`);
      if (!res.ok) throw new Error('Failed');
      const full = await res.json();
      const content = full.current_content || '';
      const lang = full.language || doc.language || 'text';

      // PDF-backed docs have a marker comment in their markdown — show the
      // rendered PDF in an iframe instead of dumping markdown source.
      const isPdfDoc = /<!--\s*pdf_(?:form_)?source\s+upload_id="[^"]+"/.test(content);
      const existingFrame = preview.querySelector('.doclib-card-pdf-frame');

      if (isPdfDoc) {
        const frame = document.createElement('iframe');
        frame.className = 'doclib-card-pdf-frame';
        frame.src = `${API_BASE}/api/document/${doc.id}/render-pdf?t=${Date.now()}`;
        frame.style.cssText = 'width:100%;height:60vh;border:1px solid var(--border);border-radius:6px;background:var(--bg);opacity:0;transition:opacity 0.15s ease;';
        if (existingPre) existingPre.remove();
        if (existingFrame) existingFrame.remove();
        preview.insertBefore(frame, preview.firstChild);
        if (actionsBar && !preview.contains(actionsBar)) preview.appendChild(actionsBar);
        requestAnimationFrame(() => { frame.style.opacity = '1'; });
        return;
      }

      const pre = document.createElement('pre');
      const code = document.createElement('code');
      // Syntax highlighting is synchronous and O(n) — running it over a whole
      // large document froze the main thread on click (the "lag"). Only
      // highlight up to a cap; bigger docs render as plain text (still fully
      // shown) so the preview opens instantly. Markdown gains little from
      // highlighting anyway, so skip it there.
      const HL_CAP = 20000;
      try {
        if (lang && lang !== 'text' && lang !== 'markdown' && window.hljs && content.length <= HL_CAP) {
          code.innerHTML = window.hljs.highlight(content, { language: lang }).value;
        } else {
          code.textContent = content;
        }
      } catch {
        code.textContent = content;
      }
      pre.appendChild(code);

      // Swap content — fade in the full version
      if (existingPre) existingPre.remove();
      if (existingFrame) existingFrame.remove();
      pre.style.opacity = '0';
      preview.insertBefore(pre, preview.firstChild);
      if (actionsBar && !preview.contains(actionsBar)) preview.appendChild(actionsBar);
      requestAnimationFrame(() => {
        pre.style.transition = 'opacity 0.15s ease';
        pre.style.opacity = '1';
      });
    } catch (e) {
      // On error, keep existing preview if available
      if (!existingPre) {
        preview.innerHTML = '<div style="padding:8px;color:var(--color-error);font-size:10px;">Failed to load</div>';
      }
      if (actionsBar && !preview.contains(actionsBar)) preview.appendChild(actionsBar);
    }
  }

  function libraryRenderLoadMore() {
    // Documents now reveal in 20-at-a-time chunks via the inline "Load more"
    // rendered inside libraryRenderGrid (matching the Chats tab). The legacy
    // server-pagination button + auto-fill are retired to avoid a double
    // control and surprise auto-loading.
    const legacy = document.getElementById('doclib-load-more');
    if (legacy) legacy.style.display = 'none';
  }

  async function libraryOpenDocument(doc) {
    closeLibrary();
    // Orphaned doc (session deleted) — just open in editor without switching session
    if (!doc.session_id) {
      _loadDocument(doc.id);
      return;
    }
    const currentSessionId = sessionModule && sessionModule.getCurrentSessionId();
    if (doc.session_id !== currentSessionId) {
      await sessionModule.selectSession(doc.session_id);
    }
    _loadDocument(doc.id);
  }

  /** Open a document in its linked session */
  async function libraryOpenInSession(doc) {
    if (!doc.session_id) return;
    closeLibrary();

    // Step 1: switch session if needed and wait for it to load
    const currentSessionId = sessionModule && sessionModule.getCurrentSessionId();
    if (doc.session_id !== currentSessionId) {
      await sessionModule.selectSession(doc.session_id);
      // Give the session UI a moment to settle
      await new Promise(r => setTimeout(r, 150));
    }

    // Step 2: ensure doc is in tabs
    const docs = _getDocs();
    if (!docs.has(doc.id)) {
      const res = await fetch(`${API_BASE}/api/document/${doc.id}`);
      if (res.ok) {
        const full = await res.json();
        _addDocToTabs(full, doc.session_id);
      }
    }

    // Step 3: open panel (slide-in is handled by openPanel)
    if (!_isOpenFn()) _openPanel();

    _switchToDoc(doc.id);
    _syncDocIndicator();
  }

  /** Copy a document from the library into the current session */
  async function libraryImportDocument(doc) {
    let sessionId = sessionModule && sessionModule.getCurrentSessionId();
    if (!sessionId) {
      // Create a new session if none exists
      if (sessionModule && sessionModule.hasPendingChat && sessionModule.hasPendingChat()) {
        const ok = await sessionModule.materializePendingSession();
        if (ok) sessionId = sessionModule.getCurrentSessionId();
      }
      if (!sessionId) {
        // No pending chat either — trigger new session, preserving the current model
        const curModel = sessionModule.getCurrentModel ? sessionModule.getCurrentModel() : null;
        const sessions = sessionModule ? sessionModule.getSessions() : [];
        // Prefer the session matching the current model, otherwise fall back to first with a model
        const withModel = sessions.filter(s => s.endpoint_url && s.model);
        const match = (curModel && withModel.find(s => s.model === curModel)) || withModel[0];
        if (match) {
          sessionModule.createDirectChat(match.endpoint_url, match.model, match.endpoint_id);
          const ok = await sessionModule.materializePendingSession();
          if (ok) sessionId = sessionModule.getCurrentSessionId();
        }
      }
      if (!sessionId) {
        if (uiModule) uiModule.showError('Could not create a session');
        return;
      }
    }
    try {
      // Fetch full content of the source document
      const srcRes = await fetch(`${API_BASE}/api/document/${doc.id}`);
      if (!srcRes.ok) throw new Error('Failed to fetch document');
      const src = await srcRes.json();

      // Deduplicate title — append (2), (3), etc. if name already exists in session
      let baseTitle = src.title || doc.title || 'Untitled';
      const existingTitles = new Set();
      const docs = _getDocs();
      for (const [, d] of docs) {
        if (d.sessionId === sessionId && d.title) existingTitles.add(d.title);
      }
      if (existingTitles.has(baseTitle)) {
        // Strip existing (N) suffix to get the root name
        const root = baseTitle.replace(/\s*\(\d+\)$/, '');
        let n = 2;
        while (existingTitles.has(root + ' (' + n + ')')) n++;
        baseTitle = root + ' (' + n + ')';
      }

      // Create a new document copy in the current session
      const res = await fetch(`${API_BASE}/api/document`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: sessionId,
          // Preserve the source's type; default to markdown when unknown
          // (the backend also sniffs, but this keeps the tab label correct).
          language: src.language || doc.language || 'markdown',
          content: src.current_content || '',
        }),
      });
      if (!res.ok) throw new Error('Failed to create document');
      const created = await res.json();
      closeLibrary();
      _addDocToTabs(created, sessionId);
      if (!_isOpenFn()) _openPanel();

      _switchToDoc(created.id);
      _syncDocIndicator();
      if (uiModule) uiModule.showToast('Document cloned to session');
    } catch (e) {
      console.error('Failed to import document:', e);
      if (uiModule) uiModule.showError('Failed to import document');
    }
  }

  // ---- Library bulk operations ----

  function libraryEnterSelectMode() {
    _librarySelectMode = true;
    _librarySelectedIds.clear();
    const bulkBar = document.getElementById('doclib-bulk-bar');
    const selectBtn = document.getElementById('doclib-select-btn');
    if (bulkBar) bulkBar.classList.remove('hidden');
    if (selectBtn) { selectBtn.classList.add('active'); selectBtn.textContent = 'Cancel'; }
    libraryUpdateBulkCount();
    libraryRenderGrid();
  }

  function libraryExitSelectMode() {
    _librarySelectMode = false;
    _librarySelectedIds.clear();
    const bulkBar = document.getElementById('doclib-bulk-bar');
    const selectBtn = document.getElementById('doclib-select-btn');
    const selectAll = document.getElementById('doclib-select-all');
    if (bulkBar) bulkBar.classList.add('hidden');
    if (selectBtn) { selectBtn.classList.remove('active'); selectBtn.textContent = 'Select'; }
    if (selectAll) selectAll.checked = false;
    libraryRenderGrid();
  }

  function libraryToggleSelectItem(id) {
    if (_librarySelectedIds.has(id)) {
      _librarySelectedIds.delete(id);
    } else {
      _librarySelectedIds.add(id);
    }
    libraryUpdateBulkCount();
  }

  function libraryToggleSelectAll() {
    const selectAllEl = document.getElementById('doclib-select-all');
    if (!selectAllEl) return;
    if (selectAllEl.checked) {
      _libraryDocs.forEach(d => _librarySelectedIds.add(d.id));
    } else {
      _librarySelectedIds.clear();
    }
    libraryUpdateBulkCount();
    libraryRenderGrid();
  }

  function libraryUpdateBulkCount() {
    const countEl = document.getElementById('doclib-selected-count');
    const actionsBtn = document.getElementById('doclib-bulk-actions');
    if (countEl) countEl.textContent = `${_librarySelectedIds.size} Selected`;
    if (actionsBtn) actionsBtn.style.color = _librarySelectedIds.size > 0 ? 'var(--fg)' : '';
    // Legacy per-action buttons no longer rendered — guard so the rest of the
    // function (if anything still references them) doesn't crash.
    const deleteBtn = document.getElementById('doclib-bulk-delete');
    const exportBtn = document.getElementById('doclib-bulk-export');
    const archiveBtn = document.getElementById('doclib-bulk-archive');
    const cloneBtn = document.getElementById('doclib-bulk-clone');
    if (deleteBtn) deleteBtn.disabled = _librarySelectedIds.size === 0;
    if (exportBtn) exportBtn.disabled = _librarySelectedIds.size === 0;
    if (cloneBtn) cloneBtn.disabled = _librarySelectedIds.size === 0;
    if (archiveBtn) {
      archiveBtn.disabled = _librarySelectedIds.size === 0;
      archiveBtn.textContent = _libraryArchivedView ? 'Restore' : 'Archive';
    }
  }

  async function libraryDeleteSingle(docId, card) {
    if (uiModule && uiModule.styledConfirm) {
      const ok = await uiModule.styledConfirm('Delete this document?', { confirmText: 'Delete', danger: true });
      if (!ok) return;
    } else if (!confirm('Delete this document?')) {
      return;
    }
    try {
      const res = await fetch(`${API_BASE}/api/document/${docId}`, { method: 'DELETE', credentials: 'same-origin' });
      if (!res.ok) {
        let detail = `HTTP ${res.status}`;
        try { const j = await res.json(); if (j?.detail) detail = j.detail; } catch {}
        throw new Error(detail);
      }
      if (card) {
        card.classList.add('doclib-card-deleting');
        card.addEventListener('transitionend', () => card.remove(), { once: true });
        setTimeout(() => { if (card.parentElement) card.remove(); }, 400);
      }
      libraryRemoveDocumentFromState(docId);
      if (uiModule) uiModule.showToast('Document deleted');
    } catch (e) {
      if (uiModule) uiModule.showError(`Failed to delete document: ${e.message || e}`);
    }
  }

  async function libraryBulkDelete() {
    if (_librarySelectedIds.size === 0) return;
    const count = _librarySelectedIds.size;
    if (uiModule && uiModule.styledConfirm) {
      const ok = await uiModule.styledConfirm(
        `Delete ${count} document${count !== 1 ? 's' : ''}?`,
        { confirmText: 'Delete', danger: true }
      );
      if (!ok) return;
    } else if (!confirm(`Delete ${count} document${count !== 1 ? 's' : ''}?`)) {
      return;
    }

    let deleted = 0;
    let failed = 0;
    const deletedIds = [];
    for (const id of _librarySelectedIds) {
      try {
        const res = await fetch(`${API_BASE}/api/document/${id}`, { method: 'DELETE', credentials: 'same-origin' });
        if (res.ok) {
          deleted++;
          deletedIds.push(id);
        }
        else { failed++; console.warn('Delete failed for', id, 'status', res.status); }
      } catch (e) {
        failed++;
        console.error('Failed to delete document:', id, e);
      }
    }

    for (const id of deletedIds) {
      const card = document.querySelector(`.doclib-card[data-doc-id="${CSS.escape(String(id))}"]`);
      if (card) card.classList.add('doclib-card-deleting');
    }
    if (deletedIds.length) await new Promise(r => setTimeout(r, 320));
    libraryExitSelectMode();
    await libraryFetch(false);
    if (uiModule) {
      const msg = failed > 0
        ? `Deleted ${deleted} · ${failed} failed`
        : `Deleted ${deleted} document${deleted !== 1 ? 's' : ''}`;
      (failed > 0 ? uiModule.showError : uiModule.showToast)(msg);
    }
  }

  async function libraryBulkArchive() {
    if (_librarySelectedIds.size === 0) return;
    const toArchived = !_libraryArchivedView;
    const ids = [..._librarySelectedIds];
    let done = 0, failed = 0;
    for (const id of ids) {
      try {
        const res = await fetch(`${API_BASE}/api/document/${id}/archive?archived=${toArchived}`, { method: 'POST', credentials: 'same-origin' });
        if (res.ok) done++; else failed++;
      } catch { failed++; }
    }
    libraryExitSelectMode();
    await libraryFetch(false);
    if (uiModule) {
      const verb = toArchived ? 'Archived' : 'Restored';
      const msg = failed > 0 ? `${verb} ${done} · ${failed} failed` : `${verb} ${done} document${done !== 1 ? 's' : ''}`;
      (failed > 0 ? uiModule.showError : uiModule.showToast)(msg);
    }
  }

  // Bulk "Clone" — reuse libraryImportDocument for each selected doc.
  // It handles session resolution + a possible new-session creation once
  // (subsequent calls in the loop see the now-resolved session).
  async function libraryBulkClone() {
    if (_librarySelectedIds.size === 0) return;
    const ids = [..._librarySelectedIds];
    let done = 0, failed = 0;
    for (const id of ids) {
      const doc = _libraryDocs.find(d => d.id === id);
      if (!doc) { failed++; continue; }
      try {
        const ok = await libraryImportDocument(doc);
        if (ok === false) failed++; else done++;
      } catch { failed++; }
    }
    libraryExitSelectMode();
    if (uiModule) {
      const msg = failed > 0
        ? `Cloned ${done} · ${failed} failed`
        : `Cloned ${done} document${done !== 1 ? 's' : ''}`;
      (failed > 0 ? uiModule.showError : uiModule.showToast)(msg);
    }
  }

  async function libraryBulkExport() {
    if (_librarySelectedIds.size === 0) return;
    // More than 5 → one server-built .zip (mirrors the gallery's bulk export;
    // browsers also block a flood of individual downloads).
    if (_librarySelectedIds.size > 5) {
      const ids = [..._librarySelectedIds];
      try {
        if (uiModule) uiModule.showToast(`Zipping ${ids.length} documents…`);
        const res = await fetch(`${API_BASE}/api/documents/export-zip`, {
          method: 'POST', credentials: 'same-origin',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ ids }),
        });
        if (!res.ok) throw new Error('zip failed');
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'documents.zip';
        document.body.appendChild(a);
        a.click();
        a.remove();
        setTimeout(() => URL.revokeObjectURL(url), 2000);
        if (uiModule) uiModule.showToast(`Exported ${ids.length} documents (zip)`);
      } catch (e) {
        if (uiModule) uiModule.showError('Failed to create zip');
      }
      return;
    }
    const extMap = {
      javascript: '.js', python: '.py', html: '.html', css: '.css',
      markdown: '.md', json: '.json', yaml: '.yml', bash: '.sh',
      sql: '.sql', rust: '.rs', go: '.go', java: '.java', c: '.c', cpp: '.cpp',
      typescript: '.ts', ruby: '.rb', php: '.php', text: '.txt',
      xml: '.xml', toml: '.toml', ini: '.ini',
    };

    const docs = await Promise.all([..._librarySelectedIds].map(async id => {
      try {
        const res = await fetch(`${API_BASE}/api/document/${id}`);
        if (!res.ok) return null;
        return await res.json();
      } catch (e) {
        console.error('Failed to export document:', id, e);
        return null;
      }
    }));
    for (const doc of docs) {
      if (!doc) continue;
      const ext = extMap[doc.language] || '.txt';
      const filename = (doc.title || 'document') + (doc.title && doc.title.includes('.') ? '' : ext);
      const blob = new Blob([doc.current_content || ''], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      a.click();
      URL.revokeObjectURL(url);
    }
    if (uiModule) uiModule.showToast(`Exported ${_librarySelectedIds.size} document${_librarySelectedIds.size !== 1 ? 's' : ''}`);
  }

  /** Lazy-load SheetJS for spreadsheet parsing */
  let _xlsxReady = null;
  function ensureXLSX() {
    if (_xlsxReady) return _xlsxReady;
    if (window.XLSX) return (_xlsxReady = Promise.resolve());
    _xlsxReady = new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = 'https://cdn.jsdelivr.net/npm/xlsx/dist/xlsx.full.min.js';
      s.onload = resolve;
      s.onerror = () => reject(new Error('Failed to load XLSX library'));
      document.head.appendChild(s);
    });
    return _xlsxReady;
  }

  let _mammothReady = null;
  function ensureMammoth() {
    if (_mammothReady) return _mammothReady;
    if (window.mammoth) return (_mammothReady = Promise.resolve());
    _mammothReady = new Promise((resolve, reject) => {
      const s = document.createElement('script');
      s.src = '/static/lib/mammoth.browser.min.js';
      s.onload = resolve;
      s.onerror = () => reject(new Error('Failed to load DOCX library'));
      document.head.appendChild(s);
    });
    return _mammothReady;
  }

  /** Convert HTML from mammoth to clean markdown */
  function htmlToMarkdown(html) {
    const doc = new DOMParser().parseFromString(html, 'text/html');
    let md = '';
    function walk(node) {
      if (node.nodeType === 3) { md += node.textContent; return; }
      if (node.nodeType !== 1) return;
      const tag = node.tagName.toLowerCase();
      if (tag === 'h1') { md += '\n# '; walkChildren(node); md += '\n'; }
      else if (tag === 'h2') { md += '\n## '; walkChildren(node); md += '\n'; }
      else if (tag === 'h3') { md += '\n### '; walkChildren(node); md += '\n'; }
      else if (tag === 'h4') { md += '\n#### '; walkChildren(node); md += '\n'; }
      else if (tag === 'strong' || tag === 'b') { md += '**'; walkChildren(node); md += '**'; }
      else if (tag === 'em' || tag === 'i') { md += '*'; walkChildren(node); md += '*'; }
      else if (tag === 'a') { md += '['; walkChildren(node); md += `](${node.href || ''})`; }
      else if (tag === 'br') { md += '\n'; }
      else if (tag === 'p') { md += '\n'; walkChildren(node); md += '\n'; }
      else if (tag === 'ul' || tag === 'ol') { md += '\n'; walkChildren(node); }
      else if (tag === 'li') {
        const parent = node.parentElement?.tagName?.toLowerCase();
        if (parent === 'ol') {
          const idx = Array.from(node.parentElement.children).indexOf(node) + 1;
          md += `${idx}. `;
        } else { md += '- '; }
        walkChildren(node);
        md += '\n';
      }
      else if (tag === 'table') { md += '\n'; convertTable(node); md += '\n'; }
      else if (tag === 'img') {
        // Skip embedded base64 images — they produce huge unreadable blobs
        const src = node.src || '';
        if (!src.startsWith('data:')) {
          md += `![${node.alt || ''}](${src})`;
        } else if (node.alt) {
          md += `*[image: ${node.alt}]*`;
        }
      }
      else { walkChildren(node); }
    }
    function walkChildren(node) { for (const child of node.childNodes) walk(child); }
    function convertTable(table) {
      const rows = table.querySelectorAll('tr');
      rows.forEach((tr, i) => {
        const cells = tr.querySelectorAll('th, td');
        md += '| ' + Array.from(cells).map(c => c.textContent.trim()).join(' | ') + ' |\n';
        if (i === 0) md += '| ' + Array.from(cells).map(() => '---').join(' | ') + ' |\n';
      });
    }
    walkChildren(doc.body);
    return md.replace(/\n{3,}/g, '\n\n').trim();
  }

  /** Read file contents — handles text, spreadsheet, and DOCX formats */
  async function readFileContent(file) {
    const name = file.name.toLowerCase();
    const isSpreadsheet = name.endsWith('.xlsx') || name.endsWith('.xls') || name.endsWith('.ods');
    const isDocx = name.endsWith('.docx');

    if (isSpreadsheet) {
      await ensureXLSX();
      const buf = await file.arrayBuffer();
      const wb = window.XLSX.read(buf, { type: 'array' });
      // Convert each sheet to CSV, join with a header per sheet
      const parts = [];
      for (const sheetName of wb.SheetNames) {
        if (wb.SheetNames.length > 1) parts.push(`# Sheet: ${sheetName}`);
        parts.push(window.XLSX.utils.sheet_to_csv(wb.Sheets[sheetName]));
      }
      return parts.join('\n\n');
    }

    if (isDocx) {
      await ensureMammoth();
      const buf = await file.arrayBuffer();
      const result = await window.mammoth.convertToHtml({ arrayBuffer: buf });
      return htmlToMarkdown(result.value);
    }

    // Plain text
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = () => reject(reader.error);
      reader.readAsText(file);
    });
  }

  /** Import files from disk into the document library */
  async function libraryImportFiles(fileList) {
    const EXT_TO_LANG = {
      '.py': 'python', '.js': 'javascript', '.ts': 'typescript',
      '.html': 'html', '.htm': 'html', '.css': 'css', '.md': 'markdown',
      '.json': 'json', '.yml': 'yaml', '.yaml': 'yaml', '.sh': 'bash',
      '.bash': 'bash', '.sql': 'sql', '.rs': 'rust', '.go': 'go',
      '.java': 'java', '.c': 'c', '.cpp': 'cpp', '.h': 'c', '.hpp': 'cpp',
      '.rb': 'ruby', '.php': 'php', '.xml': 'xml',
      '.toml': 'toml', '.ini': 'ini', '.txt': '', '.log': '',
      '.cfg': 'ini', '.conf': 'ini', '.env': '', '.jsx': 'javascript',
      '.tsx': 'typescript', '.vue': 'html', '.svelte': 'html',
      '.scss': 'css', '.sass': 'css', '.less': 'css',
      '.csv': 'csv', '.tsv': 'csv',
      '.xlsx': 'csv', '.xls': 'csv', '.ods': 'csv',
      '.docx': 'markdown', '.doc': 'markdown',
    };

    let imported = 0;
    let failed = 0;
    let _firstErr = '';

    // Library imports aren't tied to a chat — the backend now accepts a
    // session-less "library" document, so no session_id is sent.
    for (const file of fileList) {
      try {
        const name = file.name;
        const dotIdx = name.lastIndexOf('.');
        const ext = dotIdx >= 0 ? name.slice(dotIdx).toLowerCase() : '';
        const baseTitle = dotIdx > 0 ? name.slice(0, dotIdx) : name;
        const language = EXT_TO_LANG[ext] !== undefined ? EXT_TO_LANG[ext] : null;

        const isSpreadsheet = ['.xlsx', '.xls', '.ods'].includes(ext);
        const isPdf = ext === '.pdf';

        if (isPdf) {
          // Backend handles save + AcroForm detection in one shot — picks the
          // right doc kind so fillable forms get clickable inputs in the PDF
          // view, and plain PDFs get the static page-image viewer.
          const fd = new FormData();
          fd.append('file', file);
          const res = await fetch(`${API_BASE}/api/documents/import-pdf`, {
            method: 'POST',
            body: fd,
          });
          if (!res.ok) {
            let _e = `HTTP ${res.status}`;
            try { const _j = await res.json(); _e = _j.detail || _j.error || _e; } catch {}
            throw new Error('PDF import failed: ' + _e);
          }
          imported++;
          continue;
        }

        if (isSpreadsheet) {
          // Multi-sheet: create one document per sheet
          await ensureXLSX();
          const buf = await file.arrayBuffer();
          const wb = window.XLSX.read(buf, { type: 'array' });
          for (const sheetName of wb.SheetNames) {
            const csv = window.XLSX.utils.sheet_to_csv(wb.Sheets[sheetName]);
            if (!csv.trim()) continue;
            const sheetTitle = wb.SheetNames.length > 1
              ? `${baseTitle} - ${sheetName}` : baseTitle;
            const res = await fetch(`${API_BASE}/api/document`, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ title: sheetTitle, language: 'csv', content: csv }),
            });
            if (!res.ok) throw new Error('Server error');
          }
          imported++;
        } else {
          const content = await readFileContent(file);
          const res = await fetch(`${API_BASE}/api/document`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ title: baseTitle, language, content }),
          });
          if (!res.ok) throw new Error('Server error');
          imported++;
        }
      } catch (e) {
        console.error('Failed to import file:', file.name, e);
        if (!_firstErr) _firstErr = (e && e.message) || String(e);
        failed++;
      }
    }

    const msg = `Imported ${imported} file${imported !== 1 ? 's' : ''}` +
      (failed ? `, ${failed} failed${_firstErr ? ' — ' + _firstErr : ''}` : '');
    if (failed && uiModule) uiModule.showError(msg);
    else if (uiModule) uiModule.showToast(msg);
    await libraryFetch(false);
  }

  export function openLibrary(opts) {
    if (_libraryOpen) {
      // Recover from stuck state: the swipe-to-dismiss in ui.js adds .hidden
      // to the modal without calling closeLibrary, so _libraryOpen can stay
      // true even though the modal is gone or invisible. Detect and reset.
      const existing = document.getElementById('doclib-modal');
      if (!existing || existing.classList.contains('hidden')) {
        if (existing) existing.remove();
        _libraryOpen = false;
      } else {
        return;
      }
    }
    _libraryOpen = true;
    _libraryImportMode = !!(opts && opts.import);
    _librarySelectMode = false;
    _librarySelectedIds.clear();
    _librarySearch = '';
    _libraryActiveLanguage = null;
    _librarySort = 'recent';
    _libraryOffset = 0;
    _libraryDocs = [];

    // Create modal
    const modal = document.createElement('div');
    modal.className = 'modal';
    modal.id = 'doclib-modal';
    modal.innerHTML = `
      <div class="modal-content doclib-modal-content" style="width:min(640px, 92vw);background:var(--bg);">
        <div class="modal-header">
          <!-- Header title + icon mirror the currently-active sub-tab (Chats /
               Documents / Research / Archive) so the user sees ONE icon at
               the top representing the section they're in, with the tab
               strip below as sub-navigation. _switchLibTab() updates this. -->
          <h4 id="doclib-header-title"><span id="doclib-header-icon" style="vertical-align:-2px;margin-right:4px;display:inline-flex;"></span><span id="doclib-header-text">Library</span></h4>
          <button class="close-btn" id="doclib-close">\u2716</button>
        </div>
        <div class="lib-tabs" id="doclib-lib-tabs" style="padding:0 10px;">
          <button class="lib-tab" data-doclib-tab="chats"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>Chats</button>
          <button class="lib-tab active" data-doclib-tab="documents"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="13" y2="17"/></svg>Documents</button>
          <button class="lib-tab" data-doclib-tab="research"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-1px;margin-right:3px;"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>Research</button>
          <button class="lib-tab" data-doclib-tab="archive"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>Archive</button>
        </div>
        <div class="modal-body" style="display:flex;flex-direction:column;gap:10px;overflow:hidden;">
          <div id="doclib-panel-chats" data-doclib-panel="chats" class="admin-card" style="display:none;flex:1;flex-direction:column;overflow:hidden;">
            <div style="display:flex;align-items:baseline;gap:8px;margin-bottom:2px;">
              <h2 style="margin:0;padding:0;line-height:1;">Chats <span id="doclib-chats-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal"></span></h2>
            </div>
            <p class="memory-desc doclib-desc">All active chat sessions. Click to open.</p>
            <div class="memory-toolbar">
              <div class="memory-category-filters">
                <select class="memory-sort-select" id="doclib-chats-sort">
                  <option value="recent">Recent</option>
                  <option value="oldest">Oldest</option>
                  <option value="most-messages">Most messages</option>
                  <option value="alpha">A\u2013Z</option>
                </select>
                <button class="memory-toolbar-btn" id="doclib-chats-select-btn">Select</button>
                <button class="memory-toolbar-btn" id="doclib-chats-tidy-btn" title="AI tidy: delete junk sessions and organize into folders"><svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" style="vertical-align:-1px;margin-right:2px;"><path d="M12 0L14.59 8.41L23 12L14.59 15.59L12 24L9.41 15.59L1 12L9.41 8.41Z"/></svg> Tidy</button>
              </div>
              <input type="text" id="doclib-chats-search" placeholder="Search chats\u2026" class="memory-search-input" />
              <div id="doclib-chats-chips" class="doclib-lang-chips"></div>
            </div>
            <div id="doclib-chats-bulk" class="memory-bulk-bar hidden" style="margin-bottom:5px;">
              <label class="memory-bulk-check-all" style="position:relative;top:0px;left:-1px;"><input type="checkbox" id="doclib-chats-select-all" style="position:relative;top:0px;"> All</label>
              <span id="doclib-chats-selected-count">0 Selected</span>
              <button class="memory-toolbar-btn" id="doclib-chats-bulk-archive" style="position:relative;top:-3px;left:2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>Archive</button>
              <button class="memory-toolbar-btn danger" id="doclib-chats-bulk-delete" style="position:relative;left:2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>Delete</button>
              <button class="memory-toolbar-btn" id="doclib-chats-bulk-cancel" title="Cancel (Esc)" style="margin-left:4px;padding:3px 6px;position:relative;left:2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
            </div>
            <div id="doclib-chats-grid" class="doclib-grid"></div>
          </div>
          <div id="doclib-panel-archive" data-doclib-panel="archive" class="admin-card" style="display:none;flex:1;flex-direction:column;overflow:hidden;">
            <div style="display:flex;align-items:baseline;gap:8px;margin-bottom:2px;">
              <h2 style="margin:0;padding:0;line-height:1;position:relative;top:2px;">Archive <span id="doclib-arc-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal"></span></h2>
            </div>
            <p class="memory-desc doclib-desc" style="position:relative;top:0.5px;">Archived sessions. Restore to make active again.</p>
            <div class="memory-toolbar">
              <div class="memory-category-filters">
                <select class="memory-sort-select" id="doclib-arc-sort">
                  <option value="recent">Recent</option>
                  <option value="oldest">Oldest</option>
                  <option value="most-messages">Most messages</option>
                  <option value="alpha">A\u2013Z</option>
                </select>
                <button class="memory-toolbar-btn" id="doclib-arc-select-btn">Select</button>
              </div>
              <input type="text" id="doclib-arc-search" placeholder="Search archive\u2026" class="memory-search-input" />
              <div id="doclib-arc-chips" class="doclib-lang-chips"></div>
            </div>
            <div id="doclib-arc-bulk" class="memory-bulk-bar hidden" style="margin-bottom:5px;">
              <label class="memory-bulk-check-all" style="position:relative;top:0px;left:1px;"><input type="checkbox" id="doclib-arc-select-all"> All</label>
              <span id="doclib-arc-selected-count">0 Selected</span>
              <button class="memory-toolbar-btn" id="doclib-arc-bulk-restore" style="position:relative;top:-3px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>Restore</button>
              <button class="memory-toolbar-btn danger" id="doclib-arc-bulk-delete"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>Delete</button>
              <button class="memory-toolbar-btn" id="doclib-arc-bulk-cancel" title="Cancel (Esc)" style="margin-left:4px;padding:3px 6px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
            </div>
            <div id="doclib-arc-grid" class="doclib-grid"></div>
          </div>
          <div id="doclib-panel-research" data-doclib-panel="research" class="admin-card" style="display:none;flex:1;flex-direction:column;overflow:hidden;">
            <div style="display:flex;align-items:baseline;gap:8px;margin-bottom:2px;margin-top:10px;">
              <h2 style="margin:0;padding:0;line-height:1;">Research <span id="doclib-research-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal"></span></h2>
            </div>
            <p class="memory-desc doclib-desc" style="position:relative;top:-1px;">Completed deep research reports. Click to view.</p>
            <div class="memory-toolbar">
              <div class="memory-category-filters">
                <select class="memory-sort-select" id="doclib-research-sort">
                  <option value="recent">Recent</option>
                  <option value="oldest">Oldest</option>
                  <option value="most-sources">Most sources</option>
                  <option value="alpha">A\u2013Z</option>
                </select>
                <button class="memory-toolbar-btn" id="doclib-research-select-btn">Select</button>
                <button class="memory-toolbar-btn" id="doclib-research-tidy-btn" title="Tidy: delete research with no sources or empty reports">Tidy</button>
              </div>
              <input type="text" id="doclib-research-search" placeholder="Search research\u2026" class="memory-search-input" />
            </div>
            <div id="doclib-research-bulk" class="memory-bulk-bar hidden" style="margin-bottom:5px;">
              <label class="memory-bulk-check-all" style="position:relative;top:0px;left:1px;"><input type="checkbox" id="doclib-research-select-all"> All</label>
              <span id="doclib-research-selected-count">0 Selected</span>
              <button class="memory-toolbar-btn" id="doclib-research-bulk-archive" style="position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>Archive</button>
              <button class="memory-toolbar-btn danger" id="doclib-research-bulk-delete" style="position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>Delete</button>
              <button class="memory-toolbar-btn" id="doclib-research-bulk-cancel" title="Cancel (Esc)" style="margin-left:4px;padding:3px 6px;position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
            </div>
            <div id="doclib-research-grid" class="doclib-grid"></div>
          </div>
          <div data-doclib-panel="documents" class="admin-card" style="flex:1;display:flex;flex-direction:column;overflow:hidden;">
            <div style="display:flex;align-items:baseline;gap:8px;margin-bottom:2px;">
              <h2 style="margin:0;padding:0;line-height:1;">Documents <span id="doclib-stats" class="memory-count" style="font-size:0.6em;opacity:0.6;font-weight:normal"></span></h2>
              <button class="memory-toolbar-btn" id="doclib-import-file-btn" title="Import files from disk" style="margin-left:auto;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:2px;"><polyline points="7 10 12 5 17 10"/><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="21" x2="19" y2="21"/></svg> Import</button>
              <button class="memory-toolbar-btn" id="doclib-create-btn" title="Create new blank document"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg> Create</button>
            </div>
            <p class="memory-desc doclib-desc">Open documents in a session, clone to a new or import new files.</p>
            <div class="memory-toolbar">
              <div class="memory-category-filters">
                <select class="memory-sort-select" id="doclib-sort">
                  <option value="recent">Recent</option>
                  <option value="oldest">Oldest</option>
                  <option value="edits">Most edits</option>
                  <option value="alpha">A\u2013Z</option>
                </select>
                <button class="memory-toolbar-btn" id="doclib-select-btn" title="Select documents">Select</button>
                <button class="memory-toolbar-btn" id="doclib-tidy-btn" title="Tidy: remove empty / junk / duplicate documents">Tidy</button>
              </div>
              <input type="text" id="doclib-search" placeholder="Search titles &amp; content\u2026" class="memory-search-input" />
              <div id="doclib-chips" class="doclib-lang-chips"></div>
            </div>
            <input type="file" id="doclib-file-input" multiple style="display:none" />
            <div id="doclib-bulk-bar" class="memory-bulk-bar hidden" style="margin-bottom:5px;">
              <label class="memory-bulk-check-all" style="position:relative;top:0px;left:1px;"><input type="checkbox" id="doclib-select-all" /> All</label>
              <span id="doclib-selected-count">0 Selected</span>
              <button id="doclib-bulk-actions" class="memory-toolbar-btn" style="position:relative;top:-2px;margin-left:auto;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px;margin-right:3px;"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>Actions <span style="opacity:0.55;font-size:9px;">&#9660;</span></button>
              <button id="doclib-bulk-cancel" class="memory-toolbar-btn" title="Cancel (Esc)" style="margin-left:4px;margin-right:4px;padding:3px 6px;position:relative;top:-2px;"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
            </div>
            <div class="doclib-grid" id="doclib-grid"></div>
            <button class="doclib-load-more" id="doclib-load-more" style="display:none">Load more</button>
          </div>
        </div>
      </div>
    `;
    document.body.appendChild(modal);

    // Make modal draggable (same logic as other modals)
    {
      const content = modal.querySelector('.modal-content');
      const header = modal.querySelector('.modal-header');
      if (content && header) {
        // Restore saved position / fullscreen state
        try {
          const saved = JSON.parse(localStorage.getItem('doclib-pos'));
          if (saved && saved.fullscreen) {
            localStorage.removeItem('doclib-pos');
          } else if (saved && saved.left && saved.top) {
            content.style.position = 'fixed';
            content.style.left = saved.left;
            content.style.top = saved.top;
            content.style.margin = '0';
            // Clamp to viewport in case window was resized
            requestAnimationFrame(() => {
              const r = content.getBoundingClientRect();
              if (r.right > window.innerWidth) content.style.left = Math.max(0, window.innerWidth - r.width - 8) + 'px';
              if (r.bottom > window.innerHeight) content.style.top = Math.max(0, window.innerHeight - r.height - 8) + 'px';
              if (r.left < 0) content.style.left = '8px';
              if (r.top < 0) content.style.top = '8px';
            });
          }
        } catch {}
        // Replaced ~150 lines of inline drag/snap/dock with one helper call.
        // Library intentionally disables top-edge fullscreen snap: that layout
        // breaks dense icon/tool rows. Side docking still works.
        const FS_CLASS = 'doclib-fullscreen';
        const enterFullscreen = () => {
          if (modal.classList.contains(FS_CLASS)) return;
          modal.classList.add(FS_CLASS);
          content.style.position = 'fixed';
          content.style.left = '0';
          content.style.top = '0';
          content.style.right = '0';
          content.style.bottom = '0';
          content.style.width = '100vw';
          content.style.maxWidth = '100vw';
          content.style.height = '100vh';
          content.style.maxHeight = '100vh';
          content.style.borderRadius = '0';
          content.style.margin = '0';
          content.style.transform = 'none';
          try { localStorage.setItem('doclib-pos', JSON.stringify({ fullscreen: true })); } catch {}
        };
        const exitFullscreen = (cx, cy) => {
          if (!modal.classList.contains(FS_CLASS)) return;
          modal.classList.remove(FS_CLASS);
          content.style.width = '';
          content.style.maxWidth = '';
          content.style.height = '';
          content.style.maxHeight = '';
          content.style.borderRadius = '';
          content.style.right = '';
          content.style.bottom = '';
          const r0 = content.getBoundingClientRect();
          const w = r0.width || Math.min(900, window.innerWidth * 0.92);
          content.style.left = Math.max(8, cx - w / 2) + 'px';
          content.style.top = Math.max(8, cy - 20) + 'px';
        };
        makeWindowDraggable(modal, {
          content,
          header,
          fsClass: FS_CLASS,
          skipSelector: '.modal-close',
          onEnterFullscreen: enterFullscreen,
          onExitFullscreen: exitFullscreen,
          enableFullscreen: false,
          onDragEnd: () => {
            try { localStorage.setItem('doclib-pos', JSON.stringify({ left: content.style.left, top: content.style.top })); } catch {}
          },
        });
      }
    }

    // Wire events
    document.getElementById('doclib-close').addEventListener('click', closeLibrary);

    // Tab switching — Chats / Documents / Archive / Research
    let _activeLibTab = (opts && opts.tab) || 'documents';
    const _tabBtns = modal.querySelectorAll('[data-doclib-tab]');
    const _tabPanels = modal.querySelectorAll('[data-doclib-panel]');

    // Client-side pagination for tabs whose API returns everything at once
    // (chats/archive/research). Render only this many initially; the
    // load-more button reveals more in chunks.
    const _LIB_PAGE_SIZE = 20;
    let _chatsVisibleLimit = _LIB_PAGE_SIZE;
    let _arcVisibleLimit = _LIB_PAGE_SIZE;
    let _researchVisibleLimit = _LIB_PAGE_SIZE;

    function _appendInlineLoadMore(grid, totalCount, currentLimit, onClick) {
      if (!grid || !grid.parentElement) return;
      // Drop the previous instance (if any) — we re-render the list from
      // scratch each pass, so the button is regenerated alongside it.
      grid.parentElement.querySelectorAll(':scope > .doclib-inline-load-more').forEach(b => b.remove());
      if (totalCount <= currentLimit) return;
      const btn = document.createElement('button');
      btn.className = 'doclib-load-more doclib-inline-load-more';
      btn.textContent = `Load more (${currentLimit} of ${totalCount})`;
      btn.addEventListener('click', onClick);
      grid.parentElement.appendChild(btn);
    }

    // SVG markup + label for each tab — used to keep the modal header
    // in sync with whichever sub-tab the user is on.
    const _TAB_HEADERS = {
      chats: {
        label: 'Chats',
        svg: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
      },
      documents: {
        label: 'Documents',
        svg: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="13" y2="17"/></svg>',
      },
      research: {
        label: 'Research',
        svg: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>',
      },
      archive: {
        label: 'Archive',
        svg: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>',
      },
    };

    function _switchLibTab(tab) {
      _activeLibTab = tab;
      _tabBtns.forEach(b => b.classList.toggle('active', b.dataset.doclibTab === tab));
      _tabPanels.forEach(p => {
        if (p.dataset.doclibPanel === tab) {
          p.style.display = 'flex';
        } else {
          p.style.display = 'none';
        }
      });
      // Sync the modal header icon + label to match the active sub-tab.
      const hdr = _TAB_HEADERS[tab];
      if (hdr) {
        const ico = document.getElementById('doclib-header-icon');
        const txt = document.getElementById('doclib-header-text');
        if (ico) ico.innerHTML = hdr.svg;
        if (txt) txt.textContent = hdr.label;
      }
      if (tab === 'chats') _renderLibChats();
      else if (tab === 'archive') _renderLibArchive();
      else if (tab === 'research') _renderLibResearch();
    }

    _tabBtns.forEach(btn => {
      btn.addEventListener('click', () => _switchLibTab(btn.dataset.doclibTab));
    });

    // ── Chats tab state ──
    let _chatsSessions = [];
    let _chatsSearch = '';
    let _chatsSort = 'recent';
    let _chatsSelectMode = false;
    const _chatsSelected = new Set();
    let _chatsModelFilter = '';

    function _renderLibChats() {
      const grid = document.getElementById('doclib-chats-grid');
      if (!grid) return;
      grid.innerHTML = '';
      grid.appendChild(spinnerModule.createLoadingRow('Loading…'));
      fetch(API_BASE + '/api/sessions', { credentials: 'same-origin' }).then(r => r.json()).then(data => {
        const raw = Array.isArray(data) ? data : (data.sessions || []);
        _chatsSessions = raw.filter(s => !s.archived);
        _renderChatsGrid();
        _renderChatsChips();
      }).catch(() => { grid.innerHTML = '<div class="doclib-empty">Failed to load</div>'; });
    }

    // Tap a chat row to expand inline: fetches the recent messages and
    // renders them as a preview with an "Open chat" button. Tap again to
    // collapse. Mirrors the documents-tab expand pattern.
    async function _toggleChatPreview(card, session) {
      const preview = card.querySelector('.doclib-chat-preview');
      if (!preview) return;
      const isOpen = card.classList.contains('doclib-card-expanded');
      // Collapse any other open preview in this grid first
      const grid = card.closest('.doclib-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-card-expanded').forEach(c => {
          if (c !== card) {
            c.classList.remove('doclib-card-expanded');
            const p = c.querySelector('.doclib-chat-preview');
            if (p) { p.style.display = 'none'; p.innerHTML = ''; }
          }
        });
      }
      if (isOpen) {
        card.classList.remove('doclib-card-expanded');
        preview.style.display = 'none';
        preview.innerHTML = '';
        return;
      }
      card.classList.add('doclib-card-expanded');
      preview.style.display = 'block';
      preview.innerHTML = '<div style="opacity:0.4;font-size:11px;padding:8px 4px;">Loading…</div>';
      try {
        const res = await fetch(`${API_BASE}/api/history/${session.id}`, { credentials: 'same-origin' });
        if (!res.ok) throw new Error('Failed');
        const data = await res.json();
        const history = Array.isArray(data) ? data : (data.history || []);
        const recent = history.filter(m => m.role === 'user' || m.role === 'assistant').slice(-5);
        const sessionModel = (session.model || '').split('/').pop();
        const msgsHtml = recent.length
          ? recent.map(m => {
              const isUser = m.role === 'user';
              const raw = m.content || '';
              const truncated = raw.length > 600 ? raw.slice(0, 600) + '…' : raw;
              // Strip thinking blocks (internal model state) and render with
              // the same markdown pipeline the chat uses.
              const cleaned = truncated
                .replace(/<think>[\s\S]*?<\/think>/g, '')
                .replace(/<think>[\s\S]*$/, '')
                .trim();
              let body;
              try {
                body = markdownModule.mdToHtml(cleaned);
              } catch { body = _esc(cleaned); }
              // Per-message model can override the session default (e.g.
              // when comparing models in the same chat).
              const msgModel = (m.metadata && (m.metadata.model || m.metadata.model_name)) || '';
              const modelTag = !isUser && (msgModel || sessionModel)
                ? `<span class="doclib-chat-msg-model">${_esc(msgModel || sessionModel)}</span>`
                : '';
              return `<div class="doclib-chat-bubble-row ${isUser ? 'user' : 'assistant'}">
                <div class="doclib-chat-bubble">
                  ${modelTag}
                  <div class="doclib-chat-bubble-body">${body}</div>
                </div>
              </div>`;
            }).join('')
          : '<div style="opacity:0.4;font-size:11px;padding:6px 4px;">No messages yet</div>';
        const isArchive = !!session.archived;
        // Archived chats get a Restore button (unarchive); active chats get the
        // Archive button. Matches the research + document archive previews.
        const archiveHtml = isArchive
          ? '<button class="doclib-chat-restore-btn">' +
              '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"/></svg>' +
              'Restore' +
            '</button>'
          : '<button class="doclib-chat-archive-btn">' +
              '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>' +
              'Archive' +
            '</button>';
        // Copy sits next to Archive on the left side of the action row.
        // Uses the same border-only secondary-action style — distinct from
        // the danger Delete (red) and the primary Open (right-aligned).
        // Copy is hidden in the Archive (keep the footer to Delete + Restore +
        // Open there). It still shows for active chats.
        const copyHtml = isArchive ? '' : '<button class="doclib-chat-copy-btn">' +
              '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>' +
              'Copy' +
            '</button>';
        const deleteHtml = '<button class="doclib-chat-delete-btn">' +
              '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>' +
              'Delete' +
            '</button>';
        preview.innerHTML =
          '<div class="doclib-chat-preview-messages">' + msgsHtml + '</div>' +
          '<div class="doclib-chat-preview-actions">' +
            deleteHtml +
            archiveHtml +
            copyHtml +
            '<button class="doclib-chat-open-btn">' +
              '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>' +
              'Open' +
            '</button>' +
          '</div>';
        const openBtn = preview.querySelector('.doclib-chat-open-btn');
        if (openBtn) openBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          if (window.sessionModule) window.sessionModule.selectSession(session.id);
          closeLibrary();
          // Also collapse the wide sidebar so the picked chat sits
          // fullscreen — same gesture as picking a session in the
          // sidebar itself on mobile. Skip on desktop where the user
          // expects the sidebar to stay where they left it.
          if (window.innerWidth <= 768) {
            const sb = document.getElementById('sidebar');
            if (sb) {
              sb.classList.add('hidden');
              try { window.syncRailSide && window.syncRailSide(); } catch (_) {}
            }
          }
        });
        const archiveBtn = preview.querySelector('.doclib-chat-archive-btn');
        if (archiveBtn) archiveBtn.addEventListener('click', async (e) => {
          e.stopPropagation();
          await fetch(API_BASE + '/api/session/' + session.id + '/archive', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
          });
          _renderLibChats();
        });
        const restoreBtn = preview.querySelector('.doclib-chat-restore-btn');
        if (restoreBtn) restoreBtn.addEventListener('click', async (e) => {
          e.stopPropagation();
          await fetch(API_BASE + '/api/session/' + session.id + '/unarchive', { method: 'POST' });
          _renderLibArchive();
        });
        const copyBtn = preview.querySelector('.doclib-chat-copy-btn');
        if (copyBtn) copyBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          _copyChatById(session.id);
        });
        const deleteBtn = preview.querySelector('.doclib-chat-delete-btn');
        if (deleteBtn) deleteBtn.addEventListener('click', async (e) => {
          e.stopPropagation();
          if (!await window.styledConfirm('Delete this chat?', { confirmText: 'Delete', danger: true })) return;
          await fetch(API_BASE + '/api/session/' + session.id, { method: 'DELETE' });
          card.style.maxHeight = `${Math.max(card.getBoundingClientRect().height, card.scrollHeight)}px`;
          card.classList.add('memory-tidy-removing');
          await new Promise(r => setTimeout(r, 520));
          if (isArchive) _renderLibArchive(); else _renderLibChats();
        });
      } catch (e) {
        preview.innerHTML = '<div style="opacity:0.5;font-size:11px;padding:6px 4px;color:var(--color-error);">Failed to load preview</div>';
      }
    }

    function _renderChatsGrid() {
      const grid = document.getElementById('doclib-chats-grid');
      if (!grid) return;
      const _csb = document.getElementById('doclib-chats-select-btn');
      if (_csb) { _csb.classList.toggle('active', _chatsSelectMode); _csb.textContent = _chatsSelectMode ? 'Cancel' : 'Select'; }
      let filtered = _chatsSessions.slice();
      if (_chatsSearch) {
        const q = _chatsSearch.toLowerCase();
        filtered = filtered.filter(s => (s.name || '').toLowerCase().includes(q) || (s.model || '').toLowerCase().includes(q));
      }
      if (_chatsModelFilter) filtered = filtered.filter(s => s.folder === _chatsModelFilter);
      if (_chatsSort === 'oldest') filtered.sort((a, b) => (a.updated_at || '') > (b.updated_at || '') ? 1 : -1);
      else if (_chatsSort === 'most-messages') filtered.sort((a, b) => (b.message_count || 0) - (a.message_count || 0));
      else if (_chatsSort === 'alpha') filtered.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
      else filtered.sort((a, b) => (b.updated_at || '') > (a.updated_at || '') ? 1 : -1);

      const stats = document.getElementById('doclib-chats-stats');
      if (stats) stats.textContent = filtered.length + ' chat' + (filtered.length !== 1 ? 's' : '');

      if (!filtered.length) {
        // Sad-mouth smiley (downturn curve) for "nothing here yet".
        const _sadIco = '<span style="vertical-align:-3px;margin-left:6px;">' + uiModule.emptyStateIcon('sad') + '</span>';
        grid.innerHTML = '<div class="doclib-empty">No chats' + _sadIco + '</div>';
        _appendInlineLoadMore(grid, 0, _chatsVisibleLimit, () => {});
        return;
      }
      const total = filtered.length;
      const visible = filtered.slice(0, _chatsVisibleLimit);
      grid.innerHTML = '';
      _maybeCascadeGrid(grid, 'chats');
      for (const s of visible) {
        const card = document.createElement('div');
        card.className = 'memory-item doclib-chat-row';
        card.style.cursor = 'pointer';
        card.dataset.sid = s.id;
        const model = (s.model || '').split('/').pop();
        const cbHtml = _chatsSelectMode ? '<input type="checkbox" class="memory-select-cb"' + (_chatsSelected.has(s.id) ? ' checked' : '') + '>' : '';
        const chatIconSvg = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.4;flex-shrink:0;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
        const chevronSvg = '<span class="doclib-card-chevron"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"/></svg></span>';
        // Msg count badge inside the title, dimmer than the name so it
        // reads as metadata at a glance. Hidden when count is 0 so
        // brand-new "New Chat" rows don't show "\u00b7 0 msgs".
        const _chatMsgs = s.message_count || 0;
        const msgCountHtml = _chatMsgs > 0
          ? '<span style="opacity:0.45;font-weight:normal;font-size:0.9em;margin-left:6px;">\u00b7 ' + _chatMsgs + ' msg' + (_chatMsgs === 1 ? '' : 's') + '</span>'
          : '';
        card.innerHTML =
          '<div class="doclib-chat-header" style="display:flex;align-items:center;width:100%;gap:6px;">' +
            cbHtml +
            '<div style="flex:1;min-width:0;">' +
              '<div class="memory-item-title">' + chatIconSvg + _esc(s.name || 'Untitled') + msgCountHtml + '</div>' +
              '<div class="memory-item-meta" style="font-size:10px;opacity:0.4;margin-top:2px;">' + [model, _relTime(s.updated_at)].filter(Boolean).join(' \u00b7 ') + '</div>' +
            '</div>' +
            chevronSvg +
            '<div class="memory-item-actions"><button class="memory-item-btn _chat-menu" title="Actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg></button></div>' +
          '</div>' +
          '<div class="doclib-chat-preview" style="display:none;"></div>';
        const cb = card.querySelector('.memory-select-cb');
        if (cb) { cb.addEventListener('click', e => e.stopPropagation()); cb.addEventListener('change', () => { if (cb.checked) _chatsSelected.add(s.id); else _chatsSelected.delete(s.id); _updateChatsCount(); }); }
        card.querySelector('._chat-menu').addEventListener('click', (e) => { e.stopPropagation(); _showLibDropdown(e.currentTarget, [
          { label: 'Open', action: () => { if (window.sessionModule) window.sessionModule.selectSession(s.id); } },
          { label: 'Copy', action: () => _copyChatById(s.id) },
          { label: 'Archive', action: async () => { await fetch(API_BASE + '/api/session/' + s.id + '/archive', { method: 'POST', headers: {'Content-Type':'application/json'} }); _renderLibChats(); } },
          { label: 'Delete', action: async () => {
            if (!await window.styledConfirm('Delete this chat?', { confirmText: 'Delete', danger: true })) return;
            await fetch(API_BASE + '/api/session/' + s.id, { method: 'DELETE' });
            card.style.maxHeight = `${Math.max(card.getBoundingClientRect().height, card.scrollHeight)}px`;
            card.classList.add('memory-tidy-removing');
            await new Promise(r => setTimeout(r, 520));
            _renderLibChats();
          }, danger: true },
        ], { onSelect: () => {
          _chatsSelectMode = true;
          _chatsSelected.add(s.id);
          document.getElementById('doclib-chats-bulk')?.classList.remove('hidden');
          _renderChatsGrid();
        } }); });
        card.addEventListener('click', (e) => {
          if (card._suppressNextClick) { card._suppressNextClick = false; return; }
          if (_chatsSelectMode) { const c = card.querySelector('.memory-select-cb'); if (c) { c.checked = !c.checked; if (c.checked) _chatsSelected.add(s.id); else _chatsSelected.delete(s.id); _updateChatsCount(); } return; }
          if (e.target.closest('._chat-menu') || e.target.closest('.memory-select-cb') || e.target.closest('.doclib-chat-open-btn')) return;
          _toggleChatPreview(card, s);
        });
        _attachLongPressMenu(card, '._chat-menu');
        grid.appendChild(card);
      }
      _appendInlineLoadMore(grid, total, _chatsVisibleLimit, () => {
        _chatsVisibleLimit += _LIB_PAGE_SIZE;
        _renderChatsGrid();
      });
    }

    function _renderChatsChips() {
      const el = document.getElementById('doclib-chats-chips');
      if (!el) return;
      const counts = {};
      _chatsSessions.forEach(s => { const f = s.folder; if (f) counts[f] = (counts[f] || 0) + 1; });
      const folders = Object.keys(counts).sort();
      if (folders.length < 1) { el.innerHTML = ''; return; }
      el.innerHTML = '';
      const mk = (label, val, count) => { const c = document.createElement('button'); c.className = 'memory-cat-chip' + (_chatsModelFilter === val ? ' active' : ''); c.textContent = label + ' (' + count + ')'; c.addEventListener('click', () => { _chatsModelFilter = _chatsModelFilter === val ? '' : val; _renderChatsGrid(); _renderChatsChips(); }); el.appendChild(c); };
      mk('all', '', _chatsSessions.length);
      folders.forEach(f => mk(f, f, counts[f]));
    }

    function _updateChatsCount() { const el = document.getElementById('doclib-chats-selected-count'); if (el) el.textContent = _chatsSelected.size + ' Selected'; }

    // Chats event listeners
    document.getElementById('doclib-chats-sort').addEventListener('change', (e) => { _chatsSort = e.target.value; _renderChatsGrid(); });
    document.getElementById('doclib-chats-search').addEventListener('input', (e) => { _chatsSearch = e.target.value.trim(); _renderChatsGrid(); });
    document.getElementById('doclib-chats-select-btn').addEventListener('click', () => { _chatsSelectMode = !_chatsSelectMode; _chatsSelected.clear(); document.getElementById('doclib-chats-bulk').classList.toggle('hidden', !_chatsSelectMode); _renderChatsGrid(); });
    document.getElementById('doclib-chats-bulk-cancel')?.addEventListener('click', () => {
      _chatsSelectMode = false; _chatsSelected.clear();
      document.getElementById('doclib-chats-bulk').classList.add('hidden');
      _renderChatsGrid();
    });
    function _chatsToggleAll() {
      const allCb = document.getElementById('doclib-chats-select-all');
      const newState = _chatsSelected.size < _chatsSessions.length;
      if (allCb) allCb.checked = newState;
      document.querySelectorAll('#doclib-chats-grid .memory-select-cb').forEach(cb => { cb.checked = newState; });
      _chatsSessions.forEach(s => { if (newState) _chatsSelected.add(s.id); else _chatsSelected.delete(s.id); });
      _updateChatsCount();
    }
    document.getElementById('doclib-chats-select-all').addEventListener('change', _chatsToggleAll);
    document.getElementById('doclib-chats-bulk').addEventListener('click', (e) => {
      if (e.target.closest('button') || e.target.closest('input')) return;
      _chatsToggleAll();
    });
    document.getElementById('doclib-chats-bulk-archive').addEventListener('click', async () => {
      const count = _chatsSelected.size;
      if (!count) return;
      const grid = document.getElementById('doclib-chats-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-card').forEach(card => {
          const sid = card.dataset.sid || card.dataset.sessionId;
          if (sid && _chatsSelected.has(sid)) {
            card.style.transition = 'opacity 0.25s, transform 0.25s';
            card.style.opacity = '0';
            card.style.transform = 'scale(0.95)';
          }
        });
      }
      await new Promise(r => setTimeout(r, 250));
      const ids = [..._chatsSelected];
      const results = await Promise.all(
        ids.map(sid => fetch(API_BASE + '/api/session/' + sid + '/archive', { method: 'POST', headers: {'Content-Type':'application/json'} })
          .then(r => ({ sid, ok: r.ok }))
          .catch(() => ({ sid, ok: false }))
        )
      );
      const failed = results.filter(r => !r.ok).map(r => r.sid);
      if (failed.length && grid) {
        grid.querySelectorAll('.doclib-card').forEach(card => {
          const sid = card.dataset.sid || card.dataset.sessionId;
          if (sid && failed.includes(sid)) {
            card.style.opacity = '';
            card.style.transform = '';
          }
        });
        if (window.uiModule) window.uiModule.showError(`Failed to archive ${failed.length} of ${ids.length} chat${ids.length > 1 ? 's' : ''}`);
      }
      _chatsSelected.clear();
      _chatsSelectMode = false;
      document.getElementById('doclib-chats-bulk').classList.add('hidden');
      _renderLibChats();
    });
    document.getElementById('doclib-chats-bulk-delete').addEventListener('click', async () => {
      const count = _chatsSelected.size;
      if (!count) return;
      if (!await window.styledConfirm(`Delete ${count} chat${count > 1 ? 's' : ''}? This cannot be undone.`, { confirmText: 'Delete', danger: true })) return;
      // Fade out selected cards
      const grid = document.getElementById('doclib-chats-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-card').forEach(card => {
          const sid = card.dataset.sid || card.dataset.sessionId;
          if (sid && _chatsSelected.has(sid)) {
            card.style.transition = 'opacity 0.25s, transform 0.25s';
            card.style.opacity = '0';
            card.style.transform = 'scale(0.95)';
          }
        });
      }
      // Delete after animation. v2 review HIGH-8: inspect each response
      // so cards that the server rejected get restored (instead of
      // staying faded out forever) and the user sees an aggregate
      // error toast.
      await new Promise(r => setTimeout(r, 250));
      const ids = [..._chatsSelected];
      const results = await Promise.all(
        ids.map(sid => fetch(API_BASE + '/api/session/' + sid, { method: 'DELETE' })
          .then(r => ({ sid, ok: r.ok }))
          .catch(() => ({ sid, ok: false }))
        )
      );
      const failed = results.filter(r => !r.ok).map(r => r.sid);
      if (failed.length && grid) {
        // Restore faded cards for the rows the server refused.
        grid.querySelectorAll('.doclib-card').forEach(card => {
          const sid = card.dataset.sid || card.dataset.sessionId;
          if (sid && failed.includes(sid)) {
            card.style.opacity = '';
            card.style.transform = '';
          }
        });
        if (window.uiModule) window.uiModule.showError(`Failed to delete ${failed.length} of ${ids.length} chat${ids.length > 1 ? 's' : ''}`);
      }
      _chatsSelected.clear();
      _chatsSelectMode = false;
      document.getElementById('doclib-chats-bulk').classList.add('hidden');
      _renderLibChats();
    });

    // Tidy button — AI cleanup + organize into folders
    document.getElementById('doclib-chats-tidy-btn').addEventListener('click', async () => {
      const tidyBtn = document.getElementById('doclib-chats-tidy-btn');
      const origHTML = tidyBtn.innerHTML;
      tidyBtn.disabled = true;
      tidyBtn.classList.add('spinning');
      tidyBtn.textContent = '';
      // Silent whirlpool, nudged up to line up with the surrounding button
      // text in the Chats header. The previous version checked
      // `window.spinnerModule` (never bound) and always fell through to a
      // plain "Tidying..." label.
      const sp = spinnerModule.create('', 'clean', 'whirlpool');
      const el = sp.createElement();
      el.style.position = 'relative';
      el.style.top = '1px';
      tidyBtn.appendChild(el);
      sp.start();
      try {
        const res = await fetch(API_BASE + '/api/sessions/auto-sort', { method: 'POST', credentials: 'same-origin' });
        const data = await res.json();
        if (!res.ok) throw new Error(data.detail || 'Tidy failed');
        if (data.status === 'ok') {
          if (window.uiModule) window.uiModule.showToast('Sorted ' + data.updated + ' sessions into ' + data.folders.length + ' folders');
          if (window.sessionModule) await window.sessionModule.loadSessions();
          _renderLibChats();
        } else {
          if (window.uiModule) window.uiModule.showToast(data.reason || 'Nothing to tidy');
        }
      } catch (e) {
        if (window.uiModule) window.uiModule.showError('Tidy: ' + e.message);
      } finally {
        tidyBtn.disabled = false;
        tidyBtn.classList.remove('spinning');
        tidyBtn.innerHTML = origHTML;
      }
    });

    // ── Archive tab state ──
    let _arcSessions = [];
    let _arcDocs = [];        // archived documents
    let _arcResearch = [];    // archived research reports
    let _arcSearch = '';
    let _arcSort = 'recent';
    let _arcSelectMode = false;
    const _arcSelected = new Set();
    let _arcModelFilter = '';
    let _arcTypeFilter = '';   // '', 'chats', 'documents', 'research'

    function _renderLibArchive() {
      const grid = document.getElementById('doclib-arc-grid');
      if (!grid) return;
      grid.innerHTML = '';
      grid.appendChild(spinnerModule.createLoadingRow('Loading…'));
      // Archive tab is the home for ALL archived items — chats, documents, and
      // research — each rendered with its own icon. Load the three in parallel.
      Promise.all([
        fetch(API_BASE + '/api/sessions/archived?limit=100&sort=recent', { credentials: 'same-origin' }).then(r => r.json()).catch(() => ({})),
        fetch(API_BASE + '/api/documents/library?archived=true&limit=50', { credentials: 'same-origin' }).then(r => r.json()).catch(() => ({})),
        fetch('/api/research/library?archived=true', { credentials: 'same-origin' }).then(r => r.json()).catch(() => ({})),
      ]).then(([s, d, r]) => {
        // These are all archived by definition — flag them so the expanded
        // chat preview hides its (redundant) "Archive" button.
        _arcSessions = (s.sessions || []).map(x => ({ ...x, archived: true }));
        _arcDocs = d.documents || [];
        _arcResearch = (r.research || []).map(x => ({ ...x, archived: true }));
        _renderArcGrid();
        _renderArcChips();
      }).catch(() => { grid.innerHTML = '<div class="doclib-empty">Failed to load</div>'; });
    }

    // Inline expand/collapse for an archived DOCUMENT card (chat-style). Loads
    // the doc content into the card's .doclib-chat-preview. Lag-safe: caps the
    // shown text and skips highlighting (archived previews are read-only peeks).
    async function _toggleArcDocPreview(card, d) {
      const preview = card.querySelector('.doclib-chat-preview');
      if (!preview) return;
      const grid = card.closest('.doclib-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-card-expanded').forEach(c => {
          if (c !== card) {
            c.classList.remove('doclib-card-expanded');
            const p = c.querySelector('.doclib-chat-preview');
            if (p) { p.style.display = 'none'; p.innerHTML = ''; }
          }
        });
      }
      if (card.classList.contains('doclib-card-expanded')) {
        card.classList.remove('doclib-card-expanded');
        preview.style.display = 'none'; preview.innerHTML = '';
        return;
      }
      card.classList.add('doclib-card-expanded');
      preview.style.display = 'block';
      preview.innerHTML = '<div style="opacity:0.4;font-size:11px;padding:8px 4px;">Loading…</div>';
      try {
        const res = await fetch(`${API_BASE}/api/document/${d.id}`, { credentials: 'same-origin' });
        if (!res.ok) throw new Error('failed');
        const full = await res.json();
        const content = (full.current_content || '').slice(0, 20000);
        const pre = document.createElement('pre');
        pre.style.cssText = 'white-space:pre-wrap;word-break:break-word;font-size:11px;margin:6px 4px;max-height:50vh;overflow:auto;';
        pre.textContent = content || '(empty document)';
        preview.innerHTML = '';
        preview.appendChild(pre);

        // Footer — uses the same visible .doclib-chat-preview-actions style as
        // the chat/research previews (the .doclib-card-expanded-actions class is
        // display:none unless inside a .doclib-card, which these archive rows
        // are not). Delete + Restore, matching the others.
        const actions = document.createElement('div');
        actions.className = 'doclib-chat-preview-actions';
        actions.innerHTML =
          '<button class="doclib-chat-delete-btn"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>Delete</button>' +
          '<button class="doclib-chat-restore-btn"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M4 9h11a5 5 0 0 1 5 5v0a5 5 0 0 1-5 5H9"/></svg>Restore</button>' +
          '<button class="doclib-chat-open-btn"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>Open</button>';
        actions.querySelector('.doclib-chat-delete-btn').addEventListener('click', async (ev) => {
          ev.stopPropagation();
          if (!await window.styledConfirm('Delete this document?', { confirmText: 'Delete', danger: true })) return;
          await fetch(`${API_BASE}/api/document/${d.id}`, { method: 'DELETE', credentials: 'same-origin' });
          _renderLibArchive();
        });
        actions.querySelector('.doclib-chat-restore-btn').addEventListener('click', async (ev) => {
          ev.stopPropagation();
          await fetch(`${API_BASE}/api/document/${d.id}/archive?archived=false`, { method: 'POST', credentials: 'same-origin' });
          _renderLibArchive();
        });
        // Open = clone the doc into the active session and surface it in the editor.
        actions.querySelector('.doclib-chat-open-btn').addEventListener('click', (ev) => {
          ev.stopPropagation();
          libraryImportDocument(d);
        });
        preview.appendChild(actions);
      } catch {
        preview.innerHTML = '<div style="opacity:0.4;font-size:11px;padding:8px 4px;">Failed to load preview</div>';
      }
    }

    function _renderArcGrid() {
      const grid = document.getElementById('doclib-arc-grid');
      if (!grid) return;
      const _asb = document.getElementById('doclib-arc-select-btn');
      if (_asb) { _asb.classList.toggle('active', _arcSelectMode); _asb.textContent = _arcSelectMode ? 'Cancel' : 'Select'; }
      let filtered = _arcSessions.slice();
      if (_arcSearch) {
        const q = _arcSearch.toLowerCase();
        filtered = filtered.filter(s => (s.name || '').toLowerCase().includes(q) || (s.model || '').toLowerCase().includes(q));
      }
      if (_arcModelFilter) filtered = filtered.filter(s => (s.model || '').split('/').pop() === _arcModelFilter);
      if (_arcSort === 'oldest') filtered.sort((a, b) => (a.updated_at || '') > (b.updated_at || '') ? 1 : -1);
      else if (_arcSort === 'most-messages') filtered.sort((a, b) => (b.message_count || 0) - (a.message_count || 0));
      else if (_arcSort === 'alpha') filtered.sort((a, b) => (a.name || '').localeCompare(b.name || ''));
      else filtered.sort((a, b) => (b.updated_at || '') > (a.updated_at || '') ? 1 : -1);

      // Archived documents + research also live here — filter them by the same search.
      const _aq = (_arcSearch || '').toLowerCase();
      let filtDocs = _aq ? _arcDocs.filter(d => (d.title || '').toLowerCase().includes(_aq)) : _arcDocs;
      let filtResearch = _aq ? _arcResearch.filter(r => (r.query || '').toLowerCase().includes(_aq)) : _arcResearch;

      // Type filter chips (Chats / Documents / Research) zero out the others.
      const _showChats = !_arcTypeFilter || _arcTypeFilter === 'chats';
      const _showDocs = !_arcTypeFilter || _arcTypeFilter === 'documents';
      const _showResearch = !_arcTypeFilter || _arcTypeFilter === 'research';
      if (!_showChats) filtered = [];
      if (!_showDocs) filtDocs = [];
      if (!_showResearch) filtResearch = [];

      const stats = document.getElementById('doclib-arc-stats');
      if (stats) stats.textContent = (filtered.length + filtDocs.length + filtResearch.length) + ' archived';

      if (!filtered.length && !filtDocs.length && !filtResearch.length) {
        // Neutral / no-smile face for "nothing archived here".
        const _neutralIco = '<span style="vertical-align:-3px;margin-left:6px;">' + uiModule.emptyStateIcon('neutral') + '</span>';
        grid.innerHTML = '<div class="doclib-empty">No archived items' + _neutralIco + '</div>';
        _appendInlineLoadMore(grid, 0, _arcVisibleLimit, () => {});
        return;
      }
      const total = filtered.length;
      const visible = filtered.slice(0, _arcVisibleLimit);
      grid.innerHTML = '';
      _maybeCascadeGrid(grid, 'archive');
      for (const s of visible) {
        const card = document.createElement('div');
        card.className = 'memory-item doclib-chat-row';
        card.style.cursor = 'pointer';
        card.dataset.sid = s.id;
        card.dataset.arckey = 'chats:' + s.id;
        const model = (s.model || '').split('/').pop();
        const cbHtml = _arcSelectMode ? '<input type="checkbox" class="memory-select-cb" data-arckey="chats:' + s.id + '"' + (_arcSelected.has('chats:' + s.id) ? ' checked' : '') + '>' : '';
        const arcIconSvg = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.5;flex-shrink:0;"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
        card.innerHTML =
          '<div class="doclib-chat-header" style="display:flex;align-items:center;width:100%;gap:6px;">' +
            cbHtml +
            '<div style="flex:1;min-width:0;">' +
              '<div class="memory-item-title">' + arcIconSvg + _esc(s.name || 'Untitled') + '</div>' +
              '<div class="memory-item-meta" style="font-size:10px;opacity:0.4;margin-top:2px;">' + [model, _relTime(s.updated_at)].filter(Boolean).join(' \u00b7 ') + '</div>' +
            '</div>' +
            '<div class="memory-item-actions"><button class="memory-item-btn _arc-menu" title="Actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg></button></div>' +
          '</div>' +
          '<div class="doclib-chat-preview" style="display:none;"></div>';
        const cb = card.querySelector('.memory-select-cb');
        if (cb) { cb.addEventListener('click', e => e.stopPropagation()); cb.addEventListener('change', () => { if (cb.checked) _arcSelected.add('chats:' + s.id); else _arcSelected.delete('chats:' + s.id); _updateArcCount(); }); }
        card.querySelector('._arc-menu').addEventListener('click', (e) => { e.stopPropagation(); _showLibDropdown(e.currentTarget, [
          { label: 'Open', action: () => { if (window.sessionModule) window.sessionModule.selectSession(s.id); } },
          { label: 'Copy', action: () => _copyChatById(s.id) },
          { label: 'Restore', action: async () => { await fetch(API_BASE + '/api/session/' + s.id + '/unarchive', { method: 'POST' }); _renderLibArchive(); } },
          { label: 'Delete', action: async () => {
            if (!await window.styledConfirm('Delete this chat permanently?', { confirmText: 'Delete', danger: true })) return;
            await fetch(API_BASE + '/api/session/' + s.id, { method: 'DELETE' });
            _renderLibArchive();
          }, danger: true },
        ], { onSelect: () => {
          _arcSelectMode = true;
          _arcSelected.add('chats:' + s.id);
          document.getElementById('doclib-arc-bulk')?.classList.remove('hidden');
          _renderArcGrid();
        } }); });
        card.addEventListener('click', (e) => {
          if (card._suppressNextClick) { card._suppressNextClick = false; return; }
          if (_arcSelectMode) { const c = card.querySelector('.memory-select-cb'); if (c) { c.checked = !c.checked; if (c.checked) _arcSelected.add('chats:' + s.id); else _arcSelected.delete('chats:' + s.id); _updateArcCount(); } return; }
          if (e.target.closest('._arc-menu') || e.target.closest('.memory-select-cb') || e.target.closest('.doclib-chat-open-btn')) return;
          _toggleChatPreview(card, s);
        });
        _attachLongPressMenu(card, '._arc-menu');
        grid.appendChild(card);
      }
      // Archived DOCUMENTS — document icon, Restore / Delete.
      const _arcDocIco = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.5;flex-shrink:0;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>';
      for (const d of filtDocs) {
        const card = document.createElement('div');
        card.className = 'memory-item doclib-chat-row';
        card.style.cursor = 'pointer';
        card.dataset.arckey = 'documents:' + d.id;
        const _dcb = _arcSelectMode ? '<input type="checkbox" class="memory-select-cb" data-arckey="documents:' + d.id + '"' + (_arcSelected.has('documents:' + d.id) ? ' checked' : '') + '>' : '';
        card.innerHTML =
          '<div class="doclib-chat-header" style="display:flex;align-items:center;width:100%;gap:6px;">' +
            _dcb +
            '<div style="flex:1;min-width:0;">' +
              '<div class="memory-item-title">' + _arcDocIco + _esc(d.title || 'Untitled') + '</div>' +
              '<div class="memory-item-meta" style="font-size:10px;opacity:0.4;margin-top:2px;">' + ['Document', (d.language || 'text'), _relTime(d.updated_at)].filter(Boolean).join(' · ') + '</div>' +
            '</div>' +
            '<div class="memory-item-actions"><button class="memory-item-btn _arc-doc-menu" title="Actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg></button></div>' +
          '</div>' +
          '<div class="doclib-chat-preview" style="display:none;"></div>';
        const _dcbEl = card.querySelector('.memory-select-cb');
        if (_dcbEl) { _dcbEl.addEventListener('click', e => e.stopPropagation()); _dcbEl.addEventListener('change', () => { if (_dcbEl.checked) _arcSelected.add('documents:' + d.id); else _arcSelected.delete('documents:' + d.id); _updateArcCount(); }); }
        card.addEventListener('click', (e) => {
          if (e.target.closest('._arc-doc-menu') || e.target.closest('.memory-select-cb')) return;
          if (_arcSelectMode) { const c = card.querySelector('.memory-select-cb'); if (c) { c.checked = !c.checked; if (c.checked) _arcSelected.add('documents:' + d.id); else _arcSelected.delete('documents:' + d.id); _updateArcCount(); } return; }
          _toggleArcDocPreview(card, d);
        });
        card.querySelector('._arc-doc-menu').addEventListener('click', (e) => { e.stopPropagation(); _showLibDropdown(e.currentTarget, [
          { label: 'Restore', action: async () => { await fetch(API_BASE + '/api/document/' + d.id + '/archive?archived=false', { method: 'POST', credentials: 'same-origin' }); _renderLibArchive(); } },
          { label: 'Delete', danger: true, action: async () => { if (!await window.styledConfirm('Delete this document?', { confirmText: 'Delete', danger: true })) return; await fetch(API_BASE + '/api/document/' + d.id, { method: 'DELETE', credentials: 'same-origin' }); _renderLibArchive(); } },
        ], { onSelect: () => {
          _arcSelectMode = true;
          _arcSelected.add('documents:' + d.id);
          document.getElementById('doclib-arc-bulk')?.classList.remove('hidden');
          _renderArcGrid();
        } }); });
        _attachLongPressMenu(card, '._arc-doc-menu');
        grid.appendChild(card);
      }
      // Archived RESEARCH — magnifier icon, Open / Restore / Delete.
      const _arcResIco = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.5;flex-shrink:0;"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>';
      for (const r of filtResearch) {
        const card = document.createElement('div');
        card.className = 'memory-item doclib-chat-row';
        card.style.cursor = 'pointer';
        card.dataset.arckey = 'research:' + r.id;
        const _rcb = _arcSelectMode ? '<input type="checkbox" class="memory-select-cb" data-arckey="research:' + r.id + '"' + (_arcSelected.has('research:' + r.id) ? ' checked' : '') + '>' : '';
        card.innerHTML =
          '<div class="doclib-chat-header" style="display:flex;align-items:center;width:100%;gap:6px;">' +
            _rcb +
            '<div style="flex:1;min-width:0;">' +
              '<div class="memory-item-title">' + _arcResIco + _esc(r.query || 'Research') + '</div>' +
              '<div class="memory-item-meta" style="font-size:10px;opacity:0.4;margin-top:2px;">' + ['Research', (r.source_count ? r.source_count + ' sources' : ''), _relTime(r.completed_at ? new Date(r.completed_at * 1000).toISOString() : '')].filter(Boolean).join(' · ') + '</div>' +
            '</div>' +
            '<div class="memory-item-actions"><button class="memory-item-btn _arc-res-menu" title="Actions"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg></button></div>' +
          '</div>' +
          '<div class="doclib-chat-preview" style="display:none;"></div>';
        const _rcbEl = card.querySelector('.memory-select-cb');
        if (_rcbEl) { _rcbEl.addEventListener('click', e => e.stopPropagation()); _rcbEl.addEventListener('change', () => { if (_rcbEl.checked) _arcSelected.add('research:' + r.id); else _arcSelected.delete('research:' + r.id); _updateArcCount(); }); }
        card.addEventListener('click', (e) => {
          if (e.target.closest('._arc-res-menu') || e.target.closest('.memory-select-cb')) return;
          if (_arcSelectMode) { const c = card.querySelector('.memory-select-cb'); if (c) { c.checked = !c.checked; if (c.checked) _arcSelected.add('research:' + r.id); else _arcSelected.delete('research:' + r.id); _updateArcCount(); } return; }
          _toggleResearchPreview(card, r);
        });
        card.querySelector('._arc-res-menu').addEventListener('click', (e) => { e.stopPropagation(); _showLibDropdown(e.currentTarget, [
          { label: 'Open', action: () => { const a = document.createElement('a'); a.href = '/api/research/report/' + r.id; a.target = '_blank'; a.rel = 'noopener'; document.body.appendChild(a); a.click(); a.remove(); } },
          { label: 'Restore', action: async () => { await fetch('/api/research/' + r.id + '/archive?archived=false', { method: 'POST', credentials: 'same-origin' }); _renderLibArchive(); } },
          { label: 'Delete', danger: true, action: async () => { if (!await window.styledConfirm('Delete this research?', { confirmText: 'Delete', danger: true })) return; await fetch('/api/research/' + r.id, { method: 'DELETE', credentials: 'same-origin' }); _renderLibArchive(); } },
        ], { onSelect: () => {
          _arcSelectMode = true;
          _arcSelected.add('research:' + r.id);
          document.getElementById('doclib-arc-bulk')?.classList.remove('hidden');
          _renderArcGrid();
        } }); });
        _attachLongPressMenu(card, '._arc-res-menu');
        grid.appendChild(card);
      }
      _appendInlineLoadMore(grid, total, _arcVisibleLimit, () => {
        _arcVisibleLimit += _LIB_PAGE_SIZE;
        _renderArcGrid();
      });
    }

    function _renderArcChips() {
      const el = document.getElementById('doclib-arc-chips');
      if (!el) return;
      // Type filters: All / Chats / Documents / Research (only the ones present).
      el.innerHTML = '';
      const mk = (label, val, count) => {
        const c = document.createElement('button');
        c.className = 'memory-cat-chip' + (_arcTypeFilter === val ? ' active' : '');
        c.textContent = label + ' (' + count + ')';
        c.addEventListener('click', () => { _arcTypeFilter = _arcTypeFilter === val ? '' : val; _renderArcGrid(); _renderArcChips(); });
        el.appendChild(c);
      };
      const total = _arcSessions.length + _arcDocs.length + _arcResearch.length;
      if (!total) return;
      mk('All', '', total);
      if (_arcSessions.length) mk('Chats', 'chats', _arcSessions.length);
      if (_arcDocs.length) mk('Documents', 'documents', _arcDocs.length);
      if (_arcResearch.length) mk('Research', 'research', _arcResearch.length);
    }

    function _updateArcCount() { const el = document.getElementById('doclib-arc-selected-count'); if (el) el.textContent = _arcSelected.size + ' Selected'; }

    // Archive event listeners
    document.getElementById('doclib-arc-sort').addEventListener('change', (e) => { _arcSort = e.target.value; _renderArcGrid(); });
    document.getElementById('doclib-arc-search').addEventListener('input', (e) => { _arcSearch = e.target.value.trim(); _renderArcGrid(); });
    document.getElementById('doclib-arc-select-btn').addEventListener('click', () => { _arcSelectMode = !_arcSelectMode; _arcSelected.clear(); document.getElementById('doclib-arc-bulk').classList.toggle('hidden', !_arcSelectMode); _renderArcGrid(); });
    document.getElementById('doclib-arc-bulk-cancel')?.addEventListener('click', () => {
      _arcSelectMode = false; _arcSelected.clear();
      document.getElementById('doclib-arc-bulk').classList.add('hidden');
      _renderArcGrid();
    });
    // Select-all toggles EVERY visible archived card (chats + docs + research),
    // keyed by the card's composite "type:id" data-arckey.
    function _arcToggleAll() {
      const cbs = document.querySelectorAll('#doclib-arc-grid .memory-select-cb');
      const newState = _arcSelected.size < cbs.length;
      const allCb = document.getElementById('doclib-arc-select-all');
      if (allCb) allCb.checked = newState;
      cbs.forEach(cb => {
        cb.checked = newState;
        const k = cb.dataset.arckey;
        if (k) { if (newState) _arcSelected.add(k); else _arcSelected.delete(k); }
      });
      _updateArcCount();
    }
    document.getElementById('doclib-arc-select-all').addEventListener('change', _arcToggleAll);
    document.getElementById('doclib-arc-bulk').addEventListener('click', (e) => {
      if (e.target.closest('button') || e.target.closest('input')) return;
      _arcToggleAll();
    });
    // Route a composite "type:id" key to the right restore / delete endpoint.
    function _arcRestoreOne(key) {
      const i = key.indexOf(':'), type = key.slice(0, i), id = key.slice(i + 1);
      if (type === 'documents') return fetch(API_BASE + '/api/document/' + id + '/archive?archived=false', { method: 'POST', credentials: 'same-origin' });
      if (type === 'research') return fetch('/api/research/' + id + '/archive?archived=false', { method: 'POST', credentials: 'same-origin' });
      return fetch(API_BASE + '/api/session/' + id + '/unarchive', { method: 'POST', credentials: 'same-origin' });
    }
    function _arcDeleteOne(key) {
      const i = key.indexOf(':'), type = key.slice(0, i), id = key.slice(i + 1);
      if (type === 'documents') return fetch(API_BASE + '/api/document/' + id, { method: 'DELETE', credentials: 'same-origin' });
      if (type === 'research') return fetch('/api/research/' + id, { method: 'DELETE', credentials: 'same-origin' });
      return fetch(API_BASE + '/api/session/' + id, { method: 'DELETE', credentials: 'same-origin' });
    }
    document.getElementById('doclib-arc-bulk-restore').addEventListener('click', async () => {
      if (!_arcSelected.size) return;
      await Promise.all([..._arcSelected].map(_arcRestoreOne));
      _arcSelected.clear(); _arcSelectMode = false;
      document.getElementById('doclib-arc-bulk').classList.add('hidden');
      _renderLibArchive();
    });
    document.getElementById('doclib-arc-bulk-delete').addEventListener('click', async () => {
      const count = _arcSelected.size;
      if (!count) return;
      if (!await window.styledConfirm(`Delete ${count} archived item${count > 1 ? 's' : ''} permanently?`, { confirmText: 'Delete', danger: true })) return;
      const grid = document.getElementById('doclib-arc-grid');
      if (grid) {
        grid.querySelectorAll('.memory-item[data-arckey]').forEach(card => {
          if (_arcSelected.has(card.dataset.arckey)) {
            card.style.transition = 'opacity 0.25s, transform 0.25s';
            card.style.opacity = '0';
            card.style.transform = 'scale(0.95)';
          }
        });
      }
      await new Promise(r => setTimeout(r, 250));
      await Promise.all([..._arcSelected].map(_arcDeleteOne));
      _arcSelected.clear();
      _arcSelectMode = false;
      document.getElementById('doclib-arc-bulk').classList.add('hidden');
      _renderLibArchive();
    });

    // ── Research tab ──
    let _researchItems = [];
    let _researchSearch = '';
    let _researchSelectMode = false;
    let _researchArchivedView = false;
    const _researchSelected = new Set();

    async function _renderLibResearch() {
      const grid = document.getElementById('doclib-research-grid');
      const stats = document.getElementById('doclib-research-stats');
      if (!grid) return;
      // Show our whirlpool spinner instead of the plain "Loading..." text.
      grid.innerHTML = '';
      try {
        const _spm = (await import('./spinner.js')).default;
        const _sp = _spm.createWhirlpool(22);
        _sp.element.style.cssText = 'margin:18px auto;display:block;';
        grid.appendChild(_sp.element);
      } catch { grid.innerHTML = '<div class="hwfit-loading">Loading…</div>'; }
      try {
        const res = await fetch('/api/research/library' + (_researchArchivedView ? '?archived=true' : ''), { credentials: 'same-origin' });
        if (!res.ok) throw new Error(res.statusText);
        const data = await res.json();
        _researchItems = data.research || data || [];
      } catch (e) {
        grid.innerHTML = `<div class="hwfit-loading">Failed to load: ${_esc(e.message)}</div>`;
        return;
      }
      _renderResearchGrid();
    }

    // Toggle inline preview for a research row. Mirrors _toggleChatPreview
     // but pulls research-specific metadata: query, sources list (truncated),
     // followed by an "Open" action that loads the full report.
    async function _toggleResearchPreview(card, item) {
      const preview = card.querySelector('.doclib-chat-preview');
      if (!preview) return;
      const isOpen = card.classList.contains('doclib-card-expanded');
      const grid = card.closest('.doclib-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-card-expanded').forEach(c => {
          if (c !== card) {
            c.classList.remove('doclib-card-expanded');
            const p = c.querySelector('.doclib-chat-preview');
            if (p) { p.style.display = 'none'; p.innerHTML = ''; }
          }
        });
      }
      if (isOpen) {
        card.classList.remove('doclib-card-expanded');
        preview.style.display = 'none';
        preview.innerHTML = '';
        return;
      }
      card.classList.add('doclib-card-expanded');
      preview.style.display = 'block';
      preview.innerHTML = '<div style="opacity:0.4;font-size:11px;padding:8px 4px;">Loading…</div>';
      let detail = item;
      try {
        // Hit the per-research detail endpoint to pull sources + summary.
        // The library list endpoint only returns lightweight metadata.
        const res = await fetch(`${API_BASE}/api/research/detail/${item.id}`, { credentials: 'same-origin' });
        if (res.ok) detail = await res.json();
      } catch {}
      const sources = Array.isArray(detail.sources) ? detail.sources : [];
      const sourcesList = sources.slice(0, 12).map((src, i) => {
        const title = _esc(src.title || src.url || `Source ${i + 1}`);
        const url = _safeResearchHref(src.url);
        return url
          ? `<li><a href="${url}" target="_blank" rel="noopener">${title}</a></li>`
          : `<li>${title}</li>`;
      }).join('');
      const sourcesHtml = sources.length
        ? `<div class="doclib-research-sources"><div class="doclib-research-section-label">Sources (${sources.length})</div><ol>${sourcesList}${sources.length > 12 ? `<li style="opacity:0.5;">…and ${sources.length - 12} more</li>` : ''}</ol></div>`
        : '';
      // The stored research JSON keeps the report under `result` (clean) /
      // `raw_report` — there's no `summary` field, so the preview was empty.
      const summary = (detail.summary || detail.report_summary || detail.result || detail.raw_report || '').toString().trim();
      const summaryHtml = summary
        ? `<div class="doclib-research-summary"><div class="doclib-research-section-label">Report</div><div>${markdownModule.mdToHtml ? markdownModule.mdToHtml(summary) : _esc(summary)}</div></div>`
        : '';
      preview.innerHTML =
        '<div class="doclib-chat-preview-messages">' +
          (summaryHtml || sourcesHtml || '<div style="opacity:0.4;font-size:11px;padding:6px 4px;">No preview available</div>') +
          (summaryHtml && sourcesHtml ? sourcesHtml : '') +
        '</div>' +
        '<div class="doclib-chat-preview-actions">' +
          '<button class="doclib-chat-delete-btn">' +
            '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>' +
            'Delete' +
          '</button>' +
          '<button class="doclib-chat-archive-btn">' +
            '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="21 8 21 21 3 21 3 8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>' +
            ((_researchArchivedView || item.archived) ? 'Restore' : 'Archive') +
          '</button>' +
          // Discuss is hidden in the Archive so the footer matches chat
          // (Delete + Restore + Open).
          (item.archived ? '' :
          '<button class="doclib-chat-discuss-btn">' +
            '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>' +
            'Discuss' +
          '</button>') +
          '<button class="doclib-chat-open-btn">' +
            '<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>' +
            'Open' +
          '</button>' +
        '</div>';
      const discussBtn = preview.querySelector('.doclib-chat-discuss-btn');
      if (discussBtn) discussBtn.addEventListener('click', async (e) => {
        e.stopPropagation();
        const _orig = discussBtn.innerHTML;
        discussBtn.disabled = true;
        discussBtn.textContent = 'Creating…';
        try {
          const _sid = detail.session_id || detail.id || item.id;
          const res = await fetch(`${API_BASE}/api/research/spinoff/${_sid}`, { method: 'POST', credentials: 'same-origin' });
          if (!res.ok) { let d = ''; try { d = (await res.json()).detail || ''; } catch {} throw new Error(d || ('HTTP ' + res.status)); }
          const payload = await res.json();
          if (window.sessionModule && payload.session_id) {
            await window.sessionModule.loadSessions().catch(() => {});
            await window.sessionModule.selectSession(payload.session_id);
          }
          closeLibrary();
        } catch (err) {
          discussBtn.disabled = false;
          discussBtn.innerHTML = _orig;
          if (uiModule) uiModule.showError('Could not start discussion: ' + (err.message || err));
        }
      });
      const openBtn = preview.querySelector('.doclib-chat-open-btn');
      if (openBtn) openBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        const a = document.createElement('a');
        a.href = '/api/research/report/' + item.id;
        a.target = '_blank';
        a.rel = 'noopener';
        document.body.appendChild(a);
        a.click();
        a.remove();
      });
      const delBtn = preview.querySelector('.doclib-chat-delete-btn');
      if (delBtn) delBtn.addEventListener('click', async (e) => {
        e.stopPropagation();
        const ok = uiModule && uiModule.styledConfirm
          ? await uiModule.styledConfirm('Delete this research report?', { confirmText: 'Delete', danger: true })
          : window.confirm('Delete this research report?');
        if (!ok) return;
        try {
          const res = await fetch(`${API_BASE}/api/research/${item.id}`, { method: 'DELETE', credentials: 'same-origin' });
          if (!res.ok) throw new Error(await res.text());
          if (item.archived) {
            _renderLibArchive();
          } else {
            _researchItems = _researchItems.filter(r => r.id !== item.id);
            _renderResearchGrid();
          }
        } catch (err) {
          if (uiModule && uiModule.showError) uiModule.showError('Failed to delete: ' + err.message);
        }
      });
      const arcBtn = preview.querySelector('.doclib-chat-archive-btn');
      if (arcBtn) arcBtn.addEventListener('click', async (e) => {
        e.stopPropagation();
        // From the main Archive tab the item is already archived → Restore and
        // refresh the archive. From the Research tab, toggle as before.
        const fromArchiveTab = !!item.archived;
        const toArchived = fromArchiveTab ? false : !_researchArchivedView;
        try {
          await fetch(`${API_BASE}/api/research/${item.id}/archive?archived=${toArchived}`, { method: 'POST', credentials: 'same-origin' });
          if (fromArchiveTab) {
            _renderLibArchive();
          } else {
            _researchItems = _researchItems.filter(r => r.id !== item.id);
            _renderResearchGrid();
          }
          if (uiModule) uiModule.showToast(toArchived ? 'Archived' : 'Restored');
        } catch { if (uiModule) uiModule.showError('Failed to ' + (toArchived ? 'archive' : 'restore')); }
      });
    }

    function _renderResearchGrid() {
      const grid = document.getElementById('doclib-research-grid');
      const stats = document.getElementById('doclib-research-stats');
      if (!grid) return;
      const _rsb = document.getElementById('doclib-research-select-btn');
      if (_rsb) { _rsb.classList.toggle('active', _researchSelectMode); _rsb.textContent = _researchSelectMode ? 'Cancel' : 'Select'; }
      let items = _researchItems;
      if (_researchSearch) {
        const s = _researchSearch.toLowerCase();
        items = items.filter(r => (r.query || '').toLowerCase().includes(s));
      }
      // Sort
      const _rSort = document.getElementById('doclib-research-sort')?.value || 'recent';
      if (_rSort === 'recent') items.sort((a, b) => (b.completed_at || 0) - (a.completed_at || 0));
      else if (_rSort === 'oldest') items.sort((a, b) => (a.completed_at || 0) - (b.completed_at || 0));
      else if (_rSort === 'most-sources') items.sort((a, b) => (b.source_count || 0) - (a.source_count || 0));
      else if (_rSort === 'alpha') items.sort((a, b) => (a.query || '').localeCompare(b.query || ''));
      if (stats) stats.textContent = items.length + ' research' + (items.length !== 1 ? 'es' : '');
      if (!items.length) {
        grid.innerHTML =
          '<div class="hwfit-loading" style="display:flex;align-items:center;justify-content:center;gap:8px;flex-wrap:wrap;">' +
            '<span>No research yet</span>' +
            '<span style="opacity:0.7;font-size:11px;">' +
              'create one in the <a href="#" data-doclib-open-research style="color:var(--accent,var(--red));text-decoration:underline;">Deep Research</a> tab' +
            '</span>' +
          '</div>';
        grid.querySelector('[data-doclib-open-research]')?.addEventListener('click', (e) => {
          e.preventDefault();
          document.getElementById('rail-research')?.click();
        });
        _appendInlineLoadMore(grid, 0, _researchVisibleLimit, () => {});
        return;
      }
      const total = items.length;
      items = items.slice(0, _researchVisibleLimit);
      let html = '';
      for (const r of items) {
        const date = r.completed_at ? new Date(r.completed_at * 1000).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '';
        const time = r.completed_at ? new Date(r.completed_at * 1000).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '';
        const sources = r.source_count || 0;
        const duration = r.duration || '';
        const rounds = r.rounds || '';
        const selected = _researchSelected.has(r.id);
        const metaBits = [];
        if (date) metaBits.push(`${date} ${time}`);
        if (sources) metaBits.push(`${sources} sources`);
        if (rounds) metaBits.push(`${rounds} rounds`);
        if (duration) metaBits.push(`${duration}`);
        const metaText = metaBits.join(' \u00B7 ');
        html += `<div class="memory-item doclib-chat-row doclib-research-card" data-research-id="${r.id}" style="cursor:pointer;">`;
        html += `<div class="doclib-chat-header" style="display:flex;align-items:center;width:100%;gap:6px;">`;
        if (_researchSelectMode) html += `<input type="checkbox" class="memory-select-cb _res-cb" data-rid="${r.id}"${selected ? ' checked' : ''}>`;
        html += `<div style="flex:1;min-width:0;">`;
        html += `<div class="memory-item-title"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;opacity:0.4;flex-shrink:0;"><circle cx="11" cy="11" r="8"/><path d="M21 21l-4.35-4.35"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/></svg>${_esc(r.query || 'Untitled Research')}</div>`;
        html += `<div class="memory-item-meta" style="font-size:10px;opacity:0.4;margin-top:2px;">${metaText}</div>`;
        html += `</div>`;
        if (!_researchSelectMode) html += `<div class="memory-item-actions"><button class="memory-item-btn doclib-research-delete" data-rid="${r.id}" title="Delete"><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg></button></div>`;
        html += `</div>`;
        html += `<div class="doclib-chat-preview" style="display:none;"></div>`;
        html += `</div>`;
      }
      grid.innerHTML = html;
      _maybeCascadeGrid(grid, 'research');

      // Wire checkboxes
      grid.querySelectorAll('._res-cb').forEach(cb => {
        cb.addEventListener('click', e => e.stopPropagation());
        cb.addEventListener('change', () => {
          if (cb.checked) _researchSelected.add(cb.dataset.rid); else _researchSelected.delete(cb.dataset.rid);
          _updateResearchCount();
        });
      });

      // Click card → toggle preview (chat-style expand). The menu button
      // and Open-report button inside the preview are exempt.
      grid.querySelectorAll('.doclib-research-card').forEach(card => {
        card.addEventListener('click', (e) => {
          if (card._suppressNextClick) { card._suppressNextClick = false; return; }
          if (e.target.closest('.doclib-research-delete') || e.target.closest('._res-cb') || e.target.closest('.doclib-chat-open-btn')) return;
          const rid = card.dataset.researchId;
          if (_researchSelectMode) {
            const cb = card.querySelector('._res-cb');
            if (cb) { cb.checked = !cb.checked; cb.dispatchEvent(new Event('change')); }
            return;
          }
          const item = _researchItems.find(r => r.id === rid);
          if (item) _toggleResearchPreview(card, item);
        });
        _attachLongPressMenu(card, '.doclib-research-delete');
      });

      // The action button on each research row opens the actions menu
      // (Open report, Delete) — chat-style ••• menu.
      grid.querySelectorAll('.doclib-research-delete').forEach(btn => {
        btn.addEventListener('click', (e) => {
          e.stopPropagation();
          const rid = btn.dataset.rid;
          _showLibDropdown(btn, [
            { label: 'Open', action: () => {
                const a = document.createElement('a');
                a.href = '/api/research/report/' + rid;
                a.target = '_blank';
                a.rel = 'noopener';
                document.body.appendChild(a);
                a.click();
                a.remove();
              } },
            { label: _researchArchivedView ? 'Restore' : 'Archive', action: async () => {
                const toArchived = !_researchArchivedView;
                const card = btn.closest('.doclib-research-card');
                if (card) { card.style.transition = 'opacity 0.25s, transform 0.25s'; card.style.opacity = '0'; card.style.transform = 'scale(0.95)'; }
                try { await fetch('/api/research/' + rid + '/archive?archived=' + toArchived, { method: 'POST', credentials: 'same-origin' }); } catch {}
                await new Promise(r => setTimeout(r, 200));
                _researchItems = _researchItems.filter(r => r.id !== rid);
                _renderResearchGrid();
                if (uiModule) uiModule.showToast(toArchived ? 'Archived' : 'Restored');
              } },
            { label: 'Delete', danger: true, action: async () => {
                if (!await window.styledConfirm('Delete this research?', { confirmText: 'Delete', danger: true })) return;
                const card = btn.closest('.doclib-research-card');
                if (card) {
                  card.style.transition = 'opacity 0.25s, transform 0.25s';
                  card.style.opacity = '0';
                  card.style.transform = 'scale(0.95)';
                }
                await new Promise(r => setTimeout(r, 250));
                await fetch('/api/research/' + rid, { method: 'DELETE', credentials: 'same-origin' });
                _researchItems = _researchItems.filter(r => r.id !== rid);
                _renderResearchGrid();
              } },
          ], { onSelect: () => {
            _researchSelectMode = true;
            _researchSelected.add(rid);
            document.getElementById('doclib-research-bulk')?.classList.remove('hidden');
            _renderResearchGrid();
          } });
        });
      });
      _appendInlineLoadMore(grid, total, _researchVisibleLimit, () => {
        _researchVisibleLimit += _LIB_PAGE_SIZE;
        _renderResearchGrid();
      });
    }

    // Research sort + search
    const researchSortEl = document.getElementById('doclib-research-sort');
    if (researchSortEl) researchSortEl.addEventListener('change', () => _renderResearchGrid());
    const researchSearchEl = document.getElementById('doclib-research-search');
    if (researchSearchEl) {
      researchSearchEl.addEventListener('input', () => {
        _researchSearch = researchSearchEl.value.trim();
        _renderResearchGrid();
      });
    }

    function _updateResearchCount() {
      const el = document.getElementById('doclib-research-selected-count');
      if (el) el.textContent = _researchSelected.size + ' Selected';
      const arc = document.getElementById('doclib-research-bulk-archive');
      if (arc) arc.textContent = _researchArchivedView ? 'Restore' : 'Archive';
    }

    // Research select mode
    document.getElementById('doclib-research-select-btn')?.addEventListener('click', () => {
      _researchSelectMode = !_researchSelectMode;
      _researchSelected.clear();
      document.getElementById('doclib-research-bulk').classList.toggle('hidden', !_researchSelectMode);
      _renderResearchGrid();
    });

    // Research tidy — delete reports that came back empty (no sources, or
    // empty report body). Matches the Chats tidy whirlpool/borderless pattern
    // and skips confirmation per user request.
    document.getElementById('doclib-research-tidy-btn')?.addEventListener('click', async (e) => {
      const btn = e.currentTarget;
      const origHTML = btn.innerHTML;
      btn.disabled = true;
      btn.classList.add('spinning');
      btn.textContent = '';
      const sp = spinnerModule.create('', 'clean', 'whirlpool');
      const el = sp.createElement();
      el.style.position = 'relative';
      el.style.top = '1px';
      btn.appendChild(el);
      sp.start();
      try {
        const candidates = [];
        const needFetch = [];
        for (const r of _researchItems) {
          if ((r.source_count || 0) === 0) candidates.push(r);
          else needFetch.push(r);
        }
        const results = await Promise.all(needFetch.map(async r => {
          try {
            const res = await fetch('/api/research/detail/' + r.id, { credentials: 'same-origin' });
            if (!res.ok) return null;
            const d = await res.json();
            // Backend JSON uses `result` (rendered) or `raw_report` (raw md).
            // If neither exists or both are tiny, treat as empty.
            const body = (d.result || d.raw_report || '').trim();
            return body.length < 200 ? r : null;
          } catch { return null; }
        }));
        for (const r of results) if (r) candidates.push(r);
        if (candidates.length === 0) {
          if (uiModule) uiModule.showToast('Nothing to tidy');
          return;
        }
        await Promise.all(candidates.map(r => fetch('/api/research/' + r.id, { method: 'DELETE', credentials: 'same-origin' }).catch(() => {})));
        const ids = new Set(candidates.map(r => r.id));
        _researchItems = _researchItems.filter(r => !ids.has(r.id));
        _renderResearchGrid();
        if (uiModule) uiModule.showToast('Deleted ' + candidates.length);
      } finally {
        sp.stop();
        btn.disabled = false;
        btn.classList.remove('spinning');
        btn.innerHTML = origHTML;
      }
    });
    document.getElementById('doclib-research-archived-btn')?.addEventListener('click', (e) => {
      _researchArchivedView = !_researchArchivedView;
      e.currentTarget.classList.toggle('active', _researchArchivedView);
      e.currentTarget.title = _researchArchivedView ? 'Show active research' : 'Show archived research';
      if (_researchSelectMode) { _researchSelectMode = false; _researchSelected.clear(); document.getElementById('doclib-research-bulk').classList.add('hidden'); }
      _renderLibResearch();
    });
    document.getElementById('doclib-research-bulk-cancel')?.addEventListener('click', () => {
      _researchSelectMode = false;
      _researchSelected.clear();
      document.getElementById('doclib-research-bulk').classList.add('hidden');
      _renderResearchGrid();
    });

    // Research select all
    document.getElementById('doclib-research-select-all')?.addEventListener('change', () => {
      const allCb = document.getElementById('doclib-research-select-all');
      const newState = allCb?.checked;
      _researchItems.forEach(r => { if (newState) _researchSelected.add(r.id); else _researchSelected.delete(r.id); });
      _updateResearchCount();
      _renderResearchGrid();
    });

    // Research bulk delete
    document.getElementById('doclib-research-bulk-delete')?.addEventListener('click', async () => {
      const count = _researchSelected.size;
      if (!count) return;
      if (!await window.styledConfirm(`Delete ${count} research report${count > 1 ? 's' : ''} permanently?`, { confirmText: 'Delete', danger: true })) return;
      const grid = document.getElementById('doclib-research-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-research-card').forEach(card => {
          if (_researchSelected.has(card.dataset.researchId)) {
            card.style.transition = 'opacity 0.25s, transform 0.25s';
            card.style.opacity = '0';
            card.style.transform = 'scale(0.95)';
          }
        });
      }
      await new Promise(r => setTimeout(r, 250));
      await Promise.all([..._researchSelected].map(rid => fetch('/api/research/' + rid, { method: 'DELETE', credentials: 'same-origin' })));
      _researchItems = _researchItems.filter(r => !_researchSelected.has(r.id));
      _researchSelected.clear();
      _researchSelectMode = false;
      document.getElementById('doclib-research-bulk').classList.add('hidden');
      _renderResearchGrid();
    });

    // Research bulk archive / restore
    document.getElementById('doclib-research-bulk-archive')?.addEventListener('click', async () => {
      const count = _researchSelected.size;
      if (!count) return;
      const toArchived = !_researchArchivedView;
      const grid = document.getElementById('doclib-research-grid');
      if (grid) {
        grid.querySelectorAll('.doclib-research-card').forEach(card => {
          if (_researchSelected.has(card.dataset.researchId)) {
            card.style.transition = 'opacity 0.25s, transform 0.25s';
            card.style.opacity = '0';
            card.style.transform = 'scale(0.95)';
          }
        });
      }
      await new Promise(r => setTimeout(r, 250));
      await Promise.all([..._researchSelected].map(rid => fetch('/api/research/' + rid + '/archive?archived=' + toArchived, { method: 'POST', credentials: 'same-origin' })));
      _researchItems = _researchItems.filter(r => !_researchSelected.has(r.id));
      _researchSelected.clear();
      _researchSelectMode = false;
      document.getElementById('doclib-research-bulk').classList.add('hidden');
      _renderResearchGrid();
      if (uiModule) uiModule.showToast(toArchived ? 'Archived' : 'Restored');
    });

    // Shared dropdown for chats/archive menus — defined at module scope below
    // (was here originally; hoisted so libraryCreateCard's mobile kebab
    // handler — which lives outside openLibrary's closure — can call it).

    function _relTime(iso) {
      if (!iso) return '';
      const diff = Date.now() - new Date(iso).getTime();
      const mins = Math.floor(diff / 60000);
      if (mins < 60) return mins + 'm ago';
      const hrs = Math.floor(mins / 60);
      if (hrs < 24) return hrs + 'h ago';
      const days = Math.floor(hrs / 24);
      if (days < 30) return days + 'd ago';
      return new Date(iso).toLocaleDateString();
    }

    // Switch to the initial tab. Always call this — even when the
    // default ('documents') matches — so the modal header's icon + label
    // sync from "Library" to the active sub-tab on first open.
    _switchLibTab(_activeLibTab);

    const searchInput = document.getElementById('doclib-search');
    searchInput.addEventListener('input', () => {
      clearTimeout(_librarySearchDebounce);
      _librarySearchDebounce = setTimeout(() => {
        _librarySearch = searchInput.value.trim();
        libraryFetch(false);
      }, 300);
    });

    document.getElementById('doclib-sort').addEventListener('change', (e) => {
      _librarySort = e.target.value;
      libraryFetch(false);
    });

    document.getElementById('doclib-load-more').addEventListener('click', () => {
      _libraryOffset = _libraryDocs.length;
      libraryFetch(true);
    });

    // Show "Load more" only when scrolled near bottom
    const grid = document.getElementById('doclib-grid');
    if (grid) {
      grid.addEventListener('scroll', () => libraryRenderLoadMore());
      // Auto-fill on resize (fullscreen toggle, window resize, sidebar
      // toggle): re-run the load-more check so newly-revealed empty
      // space below the last card pulls in the next page automatically.
      if (typeof ResizeObserver !== 'undefined') {
        new ResizeObserver(() => libraryRenderLoadMore()).observe(grid);
      }
    }

    // Wire file import button
    const importFileBtn = document.getElementById('doclib-import-file-btn');
    const fileInput = document.getElementById('doclib-file-input');
    if (importFileBtn && fileInput) {
      importFileBtn.addEventListener('click', () => fileInput.click());
      fileInput.addEventListener('change', async () => {
        if (fileInput.files.length === 0) return;
        const files = Array.from(fileInput.files);
        fileInput.value = '';
        // Swap the import icon for a whirlpool while files upload.
        const _orig = importFileBtn.innerHTML;
        importFileBtn.disabled = true;
        let _sp = null;
        try {
          _sp = spinnerModule.createWhirlpool(12);
          _sp.element.style.cssText = 'width:12px;height:12px;margin:0 4px 0 0;display:inline-block;vertical-align:middle;position:relative;top:-2px;';
          importFileBtn.innerHTML = '';
          importFileBtn.appendChild(_sp.element);
          importFileBtn.appendChild(document.createTextNode('Import'));
        } catch {}
        try {
          await libraryImportFiles(files);
        } finally {
          try { _sp && _sp.stop(); } catch {}
          importFileBtn.innerHTML = _orig;
          importFileBtn.disabled = false;
        }
      });
    }

    // Create button — new blank document
    const createBtn = document.getElementById('doclib-create-btn');
    if (createBtn) {
      createBtn.addEventListener('click', async () => {
        // Create a new session, then create a blank document in it
        try {
          const sRes = await fetch('/api/session', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'Untitled Document' }) });
          const sData = await sRes.json();
          const sessionId = sData.session_id;
          await _createDocument(sessionId);
          // Close library and open the new session
          closeLibrary();
          if (window.sessionsModule) window.sessionsModule.loadSession(sessionId);
          setTimeout(() => _openPanel(), 300);
        } catch (e) {
          console.error('Failed to create document:', e);
          if (uiModule) uiModule.showError('Failed to create document');
        }
      });
    }

    // Archived toggle — flip the Documents list between active and archived.
    const archivedBtn = document.getElementById('doclib-archived-btn');
    if (archivedBtn) archivedBtn.addEventListener('click', () => {
      _libraryArchivedView = !_libraryArchivedView;
      archivedBtn.classList.toggle('active', _libraryArchivedView);
      archivedBtn.title = _libraryArchivedView ? 'Show active documents' : 'Show archived documents';
      if (_librarySelectMode) libraryExitSelectMode();
      libraryFetch(false);
    });

    // Tidy button — remove empty/broken documents
    const tidyBtn = document.getElementById('doclib-tidy-btn');
    if (tidyBtn) tidyBtn.addEventListener('click', async () => {
      tidyBtn.disabled = true;
      tidyBtn.classList.add('spinning');
      const origHTML = tidyBtn.innerHTML;
      tidyBtn.textContent = '';
      const spinner = spinnerModule.create('', 'clean', 'whirlpool');
      const _spEl = spinner.createElement();
      // Optical alignment: whirlpool reads 1px high inside the button.
      _spEl.style.position = 'relative';
      _spEl.style.top = '1px';
      tidyBtn.appendChild(_spEl);
      spinner.start();

      let totalDeleted = 0;
      let totalFixed = 0;
      let aiMessage = '';
      try {
        // Phase 1: regex tidy (empty/broken docs)
        const [res1] = await Promise.all([
          fetch(`${API_BASE}/api/documents/tidy`, { method: 'POST' }),
          new Promise(r => setTimeout(r, 600)),
        ]);
        if (res1.ok) {
          const d1 = await res1.json();
          totalDeleted += d1.deleted || 0;
          totalFixed += d1.fixed_titles || 0;
        }

        // Phase 2: AI tidy (junk/test detection)
        try {
          const res2 = await fetch(`${API_BASE}/api/documents/ai-tidy`, { method: 'POST' });
          if (res2.ok) {
            const d2 = await res2.json();
            totalDeleted += d2.deleted || 0;
            if (d2.message) aiMessage = d2.message;
          }
        } catch (_) { /* AI tidy is optional */ }

        spinner.destroy();

        if (totalDeleted === 0 && totalFixed === 0) {
          tidyBtn.innerHTML = '<span style="opacity:0.7">Already tidy</span>';
        } else {
          const msg = aiMessage || `Removed ${totalDeleted} document${totalDeleted !== 1 ? 's' : ''}`;
          if (uiModule) uiModule.showToast(msg);
          libraryFetch(false);
        }
        setTimeout(() => { tidyBtn.innerHTML = origHTML; tidyBtn.disabled = false; tidyBtn.classList.remove('spinning'); }, 1500);
      } catch (e) {
        spinner.destroy();
        console.error('Document tidy failed:', e);
        if (uiModule) uiModule.showToast('Tidy failed');
        tidyBtn.disabled = false;
        tidyBtn.classList.remove('spinning');
        tidyBtn.innerHTML = origHTML;
      }
    });

    // Select mode
    const selectBtn = document.getElementById('doclib-select-btn');
    if (selectBtn) selectBtn.addEventListener('click', () => {
      if (_librarySelectMode) libraryExitSelectMode();
      else libraryEnterSelectMode();
    });

    const selectAll = document.getElementById('doclib-select-all');
    if (selectAll) selectAll.addEventListener('change', libraryToggleSelectAll);

    // Click anywhere in the bulk bar "All" label or count area to toggle select-all
    const bulkCheckLabel = modal.querySelector('.memory-bulk-check-all');
    if (bulkCheckLabel) {
      bulkCheckLabel.addEventListener('click', (e) => {
        if (e.target === selectAll) return; // let native checkbox handle it
        e.preventDefault();
        selectAll.checked = !selectAll.checked;
        libraryToggleSelectAll();
      });
    }
    const selectedCountEl = document.getElementById('doclib-selected-count');
    if (selectedCountEl) {
      selectedCountEl.style.cursor = 'pointer';
      selectedCountEl.addEventListener('click', () => {
        selectAll.checked = !selectAll.checked;
        libraryToggleSelectAll();
      });
    }

    const bulkActionsBtn = document.getElementById('doclib-bulk-actions');
    if (bulkActionsBtn) bulkActionsBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      if (_librarySelectedIds.size === 0) {
        if (uiModule) uiModule.showToast('Select documents first');
        return;
      }
      _showLibDropdown(e.currentTarget, [
        { label: _libraryArchivedView ? 'Restore' : 'Archive', icon: _libraryArchivedView ? 'restore' : 'archive', action: libraryBulkArchive },
        { label: 'Clone', icon: 'clone', action: libraryBulkClone },
        { label: 'Export', icon: 'open', action: libraryBulkExport },
        { label: 'Delete', icon: 'delete', danger: true, action: libraryBulkDelete },
      ], { onCancel: libraryExitSelectMode });
    });

    const bulkCancelBtn = document.getElementById('doclib-bulk-cancel');
    if (bulkCancelBtn) bulkCancelBtn.addEventListener('click', libraryExitSelectMode);

    // Close on click outside modal content
    modal.addEventListener('click', (e) => {
      if (uiModule.isTouchInsideModal()) return;
      if (e.target === modal) closeLibrary();
    });

    // Escape key
    _libraryEscHandler = (e) => {
      if (e.key === 'Escape') {
        // Collapse expanded card first, then close modal on second Escape
        const expanded = document.querySelector('#doclib-grid .doclib-card-expanded');
        if (expanded) {
          _collapseExpandedCard(expanded);
        } else {
          closeLibrary();
        }
      }
    };
    document.addEventListener('keydown', _libraryEscHandler);

    // Toggle active on tool button
    const btn = document.getElementById('tool-doclib-btn');
    if (btn) btn.classList.add('active');

    libraryFetch(false);
    if (window.innerWidth >= 768) searchInput.focus();
  }

  export function closeLibrary() {
    if (!_libraryOpen) return;
    _libraryOpen = false;
    _librarySelectMode = false;
    _librarySelectedIds.clear();
    _libraryImportMode = false;
    clearTimeout(_librarySearchDebounce);

    const modal = document.getElementById('doclib-modal');
    if (modal) {
      const content = modal.querySelector('.modal-content, .doclib-modal-content');
      if (content) {
        content.classList.add('modal-closing');
        content.addEventListener('animationend', () => modal.remove(), { once: true });
        setTimeout(() => { if (modal.parentElement) modal.remove(); }, 250);
      } else {
        modal.remove();
      }
    }

    if (_libraryEscHandler) {
      document.removeEventListener('keydown', _libraryEscHandler);
      _libraryEscHandler = null;
    }

    const btn = document.getElementById('tool-doclib-btn');
    if (btn) btn.classList.remove('active');
  }

  export function isLibraryOpen() {
    return _libraryOpen;
  }