File size: 27,472 Bytes
4e1096a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { describe, it, expect } from 'vitest';
import {
  parseAuthors,
  createBookGroups,
  createWithinGroupSorter,
  createGroupSorter,
  getGroupSortValue,
  createBookSorter,
  ensureLibrarySortByType,
  ensureLibraryGroupByType,
  findGroupById,
  getGroupDisplayName,
} from '../../app/library/utils/libraryUtils';
import { Book, BooksGroup } from '../../types/book';
import { LibraryGroupByType, LibrarySortByType } from '../../types/settings';
import { BookMetadata } from '@/libs/document';

// Helper to create mock books with minimal required fields
const createMockBook = (
  overrides: Partial<Omit<Book, 'metadata'> & { metadata?: Partial<BookMetadata> }> = {},
): Book => ({
  hash: `hash-${Math.random().toString(36).substr(2, 9)}`,
  format: 'EPUB',
  title: 'Test Book',
  author: 'Test Author',
  createdAt: Date.now(),
  updatedAt: Date.now(),
  ...overrides,
  metadata: { ...overrides.metadata } as BookMetadata,
});

describe('parseAuthors', () => {
  it('should return single author as array', () => {
    expect(parseAuthors('John Smith')).toEqual(['John Smith']);
  });

  it('should split authors by comma', () => {
    expect(parseAuthors('John Smith, Jane Doe')).toEqual(['John Smith', 'Jane Doe']);
  });

  it('should split authors by ampersand', () => {
    expect(parseAuthors('John Smith & Jane Doe')).toEqual(['John Smith', 'Jane Doe']);
  });

  it('should split authors by "and"', () => {
    expect(parseAuthors('John Smith and Jane Doe')).toEqual(['John Smith', 'Jane Doe']);
  });

  it('should handle mixed separators', () => {
    expect(parseAuthors('John Smith, Jane Doe & Bob Wilson')).toEqual([
      'John Smith',
      'Jane Doe',
      'Bob Wilson',
    ]);
  });

  it('should handle "and" with commas', () => {
    expect(parseAuthors('John Smith, Jane Doe, and Bob Wilson')).toEqual([
      'John Smith',
      'Jane Doe',
      'Bob Wilson',
    ]);
  });

  it('should trim whitespace from author names', () => {
    expect(parseAuthors('  John Smith  ,  Jane Doe  ')).toEqual(['John Smith', 'Jane Doe']);
  });

  it('should return empty array for empty string', () => {
    expect(parseAuthors('')).toEqual([]);
  });

  it('should return empty array for whitespace only', () => {
    expect(parseAuthors('   ')).toEqual([]);
  });

  it('should handle single author with extra spaces', () => {
    expect(parseAuthors('  John Smith  ')).toEqual(['John Smith']);
  });
});

describe('createBookGroups', () => {
  describe('groupBy: none', () => {
    it('should return all books as flat list', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1' }),
        createMockBook({ hash: '2', title: 'Book 2' }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.None);

      expect(result).toHaveLength(2);
      expect(result.every((item) => 'format' in item)).toBe(true);
    });

    it('should filter out deleted books', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1' }),
        createMockBook({ hash: '2', title: 'Book 2', deletedAt: Date.now() }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.None);

      expect(result).toHaveLength(1);
    });
  });

  describe('groupBy: series', () => {
    it('should group books by series name', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', metadata: { series: 'Series A' } }),
        createMockBook({ hash: '2', title: 'Book 2', metadata: { series: 'Series A' } }),
        createMockBook({ hash: '3', title: 'Book 3', metadata: { series: 'Series B' } }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Series);

      const groups = result.filter((item): item is BooksGroup => 'books' in item);
      expect(groups).toHaveLength(2);

      const seriesA = groups.find((g) => g.name === 'Series A');
      expect(seriesA?.books).toHaveLength(2);

      const seriesB = groups.find((g) => g.name === 'Series B');
      expect(seriesB?.books).toHaveLength(1);
    });

    it('should leave books without series as ungrouped items', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', metadata: { series: 'Series A' } }),
        createMockBook({ hash: '2', title: 'Book 2' }), // No series
        createMockBook({ hash: '3', title: 'Book 3', metadata: {} }), // Empty metadata
      ];

      const result = createBookGroups(books, LibraryGroupByType.Series);

      const groups = result.filter((item): item is BooksGroup => 'books' in item);
      const ungrouped = result.filter((item): item is Book => 'format' in item);

      expect(groups).toHaveLength(1);
      expect(ungrouped).toHaveLength(2);
    });

    it('should handle empty series string as ungrouped', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', metadata: { series: '' } }),
        createMockBook({ hash: '2', title: 'Book 2', metadata: { series: '  ' } }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Series);

      const groups = result.filter((item): item is BooksGroup => 'books' in item);
      const ungrouped = result.filter((item): item is Book => 'format' in item);

      expect(groups).toHaveLength(0);
      expect(ungrouped).toHaveLength(2);
    });

    it('should set group updatedAt to most recent book', () => {
      const books = [
        createMockBook({
          hash: '1',
          title: 'Book 1',
          metadata: { series: 'Series A' },
          updatedAt: 1000,
        }),
        createMockBook({
          hash: '2',
          title: 'Book 2',
          metadata: { series: 'Series A' },
          updatedAt: 2000,
        }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Series);
      const group = result.find((item): item is BooksGroup => 'books' in item);

      expect(group?.updatedAt).toBe(2000);
    });
  });

  describe('groupBy: author', () => {
    it('should group books by author', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', author: 'Author A' }),
        createMockBook({ hash: '2', title: 'Book 2', author: 'Author A' }),
        createMockBook({ hash: '3', title: 'Book 3', author: 'Author B' }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Author);

      const groups = result.filter((item): item is BooksGroup => 'books' in item);
      expect(groups).toHaveLength(2);

      const authorA = groups.find((g) => g.name === 'Author A');
      expect(authorA?.books).toHaveLength(2);
    });

    it('should place book in multiple groups for multiple authors', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', author: 'John Smith, Jane Doe' }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Author);

      const groups = result.filter((item): item is BooksGroup => 'books' in item);
      expect(groups).toHaveLength(2);

      const john = groups.find((g) => g.name === 'John Smith');
      const jane = groups.find((g) => g.name === 'Jane Doe');

      expect(john?.books).toHaveLength(1);
      expect(jane?.books).toHaveLength(1);
      expect(john?.books[0]!.hash).toBe(jane?.books[0]!.hash);
    });

    it('should leave books without author as ungrouped', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', author: 'Author A' }),
        createMockBook({ hash: '2', title: 'Book 2', author: '' }),
        createMockBook({ hash: '3', title: 'Book 3', author: '   ' }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Author);

      const groups = result.filter((item): item is BooksGroup => 'books' in item);
      const ungrouped = result.filter((item): item is Book => 'format' in item);

      expect(groups).toHaveLength(1);
      expect(ungrouped).toHaveLength(2);
    });
  });

  describe('groupBy: group', () => {
    it('should return books as-is (group mode handled elsewhere)', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1' }),
        createMockBook({ hash: '2', title: 'Book 2' }),
      ];

      const result = createBookGroups(books, LibraryGroupByType.Group);

      // Group mode just returns filtered books - actual grouping is in generateBookshelfItems
      expect(result).toHaveLength(2);
    });
  });
});

describe('createWithinGroupSorter', () => {
  describe('series grouping', () => {
    it('should sort by seriesIndex ascending', () => {
      const books = [
        createMockBook({
          hash: '1',
          title: 'Book 3',
          metadata: { seriesIndex: 3 },
        }),
        createMockBook({
          hash: '2',
          title: 'Book 1',
          metadata: { seriesIndex: 1 },
        }),
        createMockBook({
          hash: '3',
          title: 'Book 2',
          metadata: { seriesIndex: 2 },
        }),
      ];

      const sorter = createWithinGroupSorter(
        LibraryGroupByType.Series,
        LibrarySortByType.Title,
        'en',
      );
      const sorted = [...books].sort(sorter);

      expect(sorted[0]!.metadata?.seriesIndex).toBe(1);
      expect(sorted[1]!.metadata?.seriesIndex).toBe(2);
      expect(sorted[2]!.metadata?.seriesIndex).toBe(3);
    });

    it('should place books without seriesIndex after those with index', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book A', metadata: {} }),
        createMockBook({ hash: '2', title: 'Book B', metadata: { seriesIndex: 1 } }),
      ];

      const sorter = createWithinGroupSorter(
        LibraryGroupByType.Series,
        LibrarySortByType.Title,
        'en',
      );
      const sorted = [...books].sort(sorter);

      expect(sorted[0]!.hash).toBe('2'); // Has index
      expect(sorted[1]!.hash).toBe('1'); // No index
    });

    it('should sort books without seriesIndex by global sort criteria', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Zebra', metadata: {} }),
        createMockBook({ hash: '2', title: 'Apple', metadata: {} }),
      ];

      const sorter = createWithinGroupSorter(
        LibraryGroupByType.Series,
        LibrarySortByType.Title,
        'en',
      );
      const sorted = [...books].sort(sorter);

      expect(sorted[0]!.title).toBe('Apple');
      expect(sorted[1]!.title).toBe('Zebra');
    });

    it('should handle decimal seriesIndex values', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 2', metadata: { seriesIndex: 2 } }),
        createMockBook({ hash: '2', title: 'Book 1.5', metadata: { seriesIndex: 1.5 } }),
        createMockBook({ hash: '3', title: 'Book 1', metadata: { seriesIndex: 1 } }),
      ];

      const sorter = createWithinGroupSorter(
        LibraryGroupByType.Series,
        LibrarySortByType.Title,
        'en',
      );
      const sorted = [...books].sort(sorter);

      expect(sorted[0]!.metadata?.seriesIndex).toBe(1);
      expect(sorted[1]!.metadata?.seriesIndex).toBe(1.5);
      expect(sorted[2]!.metadata?.seriesIndex).toBe(2);
    });
  });

  describe('author grouping', () => {
    it('should sort by global sort criteria (title)', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Zebra' }),
        createMockBook({ hash: '2', title: 'Apple' }),
      ];

      const sorter = createWithinGroupSorter(
        LibraryGroupByType.Author,
        LibrarySortByType.Title,
        'en',
      );
      const sorted = [...books].sort(sorter);

      expect(sorted[0]!.title).toBe('Apple');
      expect(sorted[1]!.title).toBe('Zebra');
    });

    it('should sort by global sort criteria (updated)', () => {
      const books = [
        createMockBook({ hash: '1', title: 'Book 1', updatedAt: 2000 }),
        createMockBook({ hash: '2', title: 'Book 2', updatedAt: 1000 }),
      ];

      const sorter = createWithinGroupSorter(
        LibraryGroupByType.Author,
        LibrarySortByType.Updated,
        'en',
      );
      const sorted = [...books].sort(sorter);

      expect(sorted[0]!.updatedAt).toBe(1000);
      expect(sorted[1]!.updatedAt).toBe(2000);
    });
  });
});

describe('getGroupSortValue', () => {
  const createMockGroup = (overrides: Partial<BooksGroup> = {}): BooksGroup => ({
    id: 'test-group',
    name: 'Test Group',
    displayName: 'Test Group',
    books: [],
    updatedAt: Date.now(),
    ...overrides,
  });

  it('should return group name for title sort', () => {
    const group = createMockGroup({ name: 'My Series' });
    expect(getGroupSortValue(group, LibrarySortByType.Title)).toBe('My Series');
  });

  it('should return group name for author sort', () => {
    const group = createMockGroup({ name: 'John Smith' });
    expect(getGroupSortValue(group, LibrarySortByType.Author)).toBe('John Smith');
  });

  it('should return group name for format sort', () => {
    const group = createMockGroup({ name: 'Test Group' });
    expect(getGroupSortValue(group, LibrarySortByType.Format)).toBe('Test Group');
  });

  it('should return max updatedAt for date read sort', () => {
    const group = createMockGroup({
      books: [
        createMockBook({ updatedAt: 1000 }),
        createMockBook({ updatedAt: 3000 }),
        createMockBook({ updatedAt: 2000 }),
      ],
    });

    expect(getGroupSortValue(group, LibrarySortByType.Updated)).toBe(3000);
  });

  it('should return max createdAt for date added sort', () => {
    const group = createMockGroup({
      books: [
        createMockBook({ createdAt: 1000 }),
        createMockBook({ createdAt: 3000 }),
        createMockBook({ createdAt: 2000 }),
      ],
    });

    expect(getGroupSortValue(group, LibrarySortByType.Created)).toBe(3000);
  });

  it('should return max published date for published sort', () => {
    const group = createMockGroup({
      books: [
        createMockBook({ metadata: { published: '2020-01-01' } }),
        createMockBook({ metadata: { published: '2023-06-15' } }),
        createMockBook({ metadata: { published: '2021-12-31' } }),
      ],
    });

    const result = getGroupSortValue(group, LibrarySortByType.Published);
    expect(result).toBe(new Date('2023-06-15').getTime());
  });

  it('should handle missing published dates', () => {
    const group = createMockGroup({
      books: [createMockBook({ metadata: {} }), createMockBook({})],
    });

    expect(getGroupSortValue(group, LibrarySortByType.Published)).toBe(0);
  });

  it('should handle empty groups gracefully', () => {
    const group = createMockGroup({ books: [] });

    // Text-based sorts return group name
    expect(getGroupSortValue(group, LibrarySortByType.Title)).toBe('Test Group');
    // Numeric sorts return 0 for empty groups
    expect(getGroupSortValue(group, LibrarySortByType.Updated)).toBe(0);
  });
});

describe('createGroupSorter', () => {
  const createMockGroup = (overrides: Partial<BooksGroup> = {}): BooksGroup => ({
    id: 'test-group',
    name: 'Test Group',
    displayName: 'Test Group',
    books: [],
    updatedAt: Date.now(),
    ...overrides,
  });

  it('should sort groups alphabetically by name for title sort', () => {
    const groups = [
      createMockGroup({ name: 'Zebra Series' }),
      createMockGroup({ name: 'Apple Series' }),
      createMockGroup({ name: 'Mango Series' }),
    ];

    const sorter = createGroupSorter(LibrarySortByType.Title, 'en');
    const sorted = [...groups].sort(sorter);

    expect(sorted[0]!.name).toBe('Apple Series');
    expect(sorted[1]!.name).toBe('Mango Series');
    expect(sorted[2]!.name).toBe('Zebra Series');
  });

  it('should sort groups by most recent updatedAt for date read sort', () => {
    const groups = [
      createMockGroup({
        name: 'Group A',
        books: [createMockBook({ updatedAt: 1000 })],
      }),
      createMockGroup({
        name: 'Group B',
        books: [createMockBook({ updatedAt: 3000 })],
      }),
      createMockGroup({
        name: 'Group C',
        books: [createMockBook({ updatedAt: 2000 })],
      }),
    ];

    const sorter = createGroupSorter(LibrarySortByType.Updated, 'en');
    const sorted = [...groups].sort(sorter);

    expect(sorted[0]!.name).toBe('Group A');
    expect(sorted[1]!.name).toBe('Group C');
    expect(sorted[2]!.name).toBe('Group B');
  });

  it('should sort groups by most recent createdAt for date added sort', () => {
    const groups = [
      createMockGroup({
        name: 'Group A',
        books: [createMockBook({ createdAt: 3000 })],
      }),
      createMockGroup({
        name: 'Group B',
        books: [createMockBook({ createdAt: 1000 })],
      }),
    ];

    const sorter = createGroupSorter(LibrarySortByType.Created, 'en');
    const sorted = [...groups].sort(sorter);

    expect(sorted[0]!.name).toBe('Group B');
    expect(sorted[1]!.name).toBe('Group A');
  });

  it('should handle groups with single book', () => {
    const groups = [
      createMockGroup({
        name: 'Group A',
        books: [createMockBook({ updatedAt: 1000 })],
      }),
      createMockGroup({
        name: 'Group B',
        books: [createMockBook({ updatedAt: 2000 })],
      }),
    ];

    const sorter = createGroupSorter(LibrarySortByType.Updated, 'en');
    const sorted = [...groups].sort(sorter);

    expect(sorted[0]!.name).toBe('Group A');
    expect(sorted[1]!.name).toBe('Group B');
  });
});

describe('createBookSorter', () => {
  it('should sort by title alphabetically', () => {
    const books = [
      createMockBook({ title: 'Zebra' }),
      createMockBook({ title: 'Apple' }),
      createMockBook({ title: 'Mango' }),
    ];

    const sorter = createBookSorter(LibrarySortByType.Title, 'en');
    const sorted = [...books].sort(sorter);

    expect(sorted[0]!.title).toBe('Apple');
    expect(sorted[1]!.title).toBe('Mango');
    expect(sorted[2]!.title).toBe('Zebra');
  });

  it('should sort by updatedAt for date read', () => {
    const books = [
      createMockBook({ title: 'Book A', updatedAt: 2000 }),
      createMockBook({ title: 'Book B', updatedAt: 1000 }),
      createMockBook({ title: 'Book C', updatedAt: 3000 }),
    ];

    const sorter = createBookSorter(LibrarySortByType.Updated, 'en');
    const sorted = [...books].sort(sorter);

    expect(sorted[0]!.title).toBe('Book B');
    expect(sorted[1]!.title).toBe('Book A');
    expect(sorted[2]!.title).toBe('Book C');
  });
});

describe('grouping and sorting integration', () => {
  it('should correctly group by series and sort groups by date read', () => {
    const books = [
      createMockBook({
        hash: '1',
        title: 'Old Series Book',
        metadata: { series: 'Old Series', seriesIndex: 1 },
        updatedAt: 1000,
      }),
      createMockBook({
        hash: '2',
        title: 'New Series Book 1',
        metadata: { series: 'New Series', seriesIndex: 1 },
        updatedAt: 3000,
      }),
      createMockBook({
        hash: '3',
        title: 'New Series Book 2',
        metadata: { series: 'New Series', seriesIndex: 2 },
        updatedAt: 2000,
      }),
    ];

    // Create groups
    const items = createBookGroups(books, LibraryGroupByType.Series);
    const groups = items.filter((item): item is BooksGroup => 'books' in item);

    // Sort groups by updated (descending - most recent first)
    const groupSorter = createGroupSorter(LibrarySortByType.Updated, 'en');
    groups.sort((a, b) => groupSorter(a, b) * -1); // Descending

    expect(groups[0]!.name).toBe('New Series'); // Most recent book at 3000
    expect(groups[1]!.name).toBe('Old Series'); // Most recent book at 1000

    // Sort within groups by seriesIndex
    const withinSorter = createWithinGroupSorter(
      LibraryGroupByType.Series,
      LibrarySortByType.Updated,
      'en',
    );
    groups.forEach((group) => group.books.sort(withinSorter));

    expect(groups[0]!.books[0]!.metadata?.seriesIndex).toBe(1);
    expect(groups[0]!.books[1]!.metadata?.seriesIndex).toBe(2);
  });

  it('should correctly group by author and sort within groups by title', () => {
    const books = [
      createMockBook({ hash: '1', title: 'Zebra', author: 'Author A' }),
      createMockBook({ hash: '2', title: 'Apple', author: 'Author A' }),
      createMockBook({ hash: '3', title: 'Mango', author: 'Author B' }),
    ];

    // Create groups
    const items = createBookGroups(books, LibraryGroupByType.Author);
    const groups = items.filter((item): item is BooksGroup => 'books' in item);

    // Sort groups alphabetically
    const groupSorter = createGroupSorter(LibrarySortByType.Title, 'en');
    groups.sort(groupSorter);

    expect(groups[0]!.name).toBe('Author A');
    expect(groups[1]!.name).toBe('Author B');

    // Sort within groups by title
    const withinSorter = createWithinGroupSorter(
      LibraryGroupByType.Author,
      LibrarySortByType.Title,
      'en',
    );
    groups.forEach((group) => group.books.sort(withinSorter));

    expect(groups[0]!.books[0]!.title).toBe('Apple');
    expect(groups[0]!.books[1]!.title).toBe('Zebra');
  });

  it('should handle ascending/descending sort order', () => {
    const books = [
      createMockBook({
        hash: '1',
        title: 'Series A Book',
        metadata: { series: 'Series A' },
        updatedAt: 1000,
      }),
      createMockBook({
        hash: '2',
        title: 'Series B Book',
        metadata: { series: 'Series B' },
        updatedAt: 2000,
      }),
    ];

    const items = createBookGroups(books, LibraryGroupByType.Series);
    const groups = items.filter((item): item is BooksGroup => 'books' in item);
    const groupSorter = createGroupSorter(LibrarySortByType.Updated, 'en');

    // Ascending (oldest first)
    const ascending = [...groups].sort((a, b) => groupSorter(a, b) * 1);
    expect(ascending[0]!.name).toBe('Series A');

    // Descending (newest first)
    const descending = [...groups].sort((a, b) => groupSorter(a, b) * -1);
    expect(descending[0]!.name).toBe('Series B');
  });
});

describe('ensureLibrarySortByType', () => {
  it('should return valid sort type when value is valid', () => {
    expect(ensureLibrarySortByType('title', LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Title,
    );
    expect(ensureLibrarySortByType('author', LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Author,
    );
    expect(ensureLibrarySortByType('updated', LibrarySortByType.Title)).toBe(
      LibrarySortByType.Updated,
    );
    expect(ensureLibrarySortByType('created', LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Created,
    );
    expect(ensureLibrarySortByType('format', LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Format,
    );
    expect(ensureLibrarySortByType('published', LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Published,
    );
  });

  it('should return fallback when value is null', () => {
    expect(ensureLibrarySortByType(null, LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Updated,
    );
  });

  it('should return fallback when value is undefined', () => {
    expect(ensureLibrarySortByType(undefined, LibrarySortByType.Title)).toBe(
      LibrarySortByType.Title,
    );
  });

  it('should return fallback when value is invalid', () => {
    expect(ensureLibrarySortByType('invalid', LibrarySortByType.Updated)).toBe(
      LibrarySortByType.Updated,
    );
    expect(ensureLibrarySortByType('random', LibrarySortByType.Title)).toBe(
      LibrarySortByType.Title,
    );
  });

  it('should return fallback when value is empty string', () => {
    expect(ensureLibrarySortByType('', LibrarySortByType.Updated)).toBe(LibrarySortByType.Updated);
  });
});

describe('ensureLibraryGroupByType', () => {
  it('should return valid group type when value is valid', () => {
    expect(ensureLibraryGroupByType('none', LibraryGroupByType.Group)).toBe(
      LibraryGroupByType.None,
    );
    expect(ensureLibraryGroupByType('group', LibraryGroupByType.None)).toBe(
      LibraryGroupByType.Group,
    );
    expect(ensureLibraryGroupByType('series', LibraryGroupByType.Group)).toBe(
      LibraryGroupByType.Series,
    );
    expect(ensureLibraryGroupByType('author', LibraryGroupByType.Group)).toBe(
      LibraryGroupByType.Author,
    );
  });

  it('should return fallback when value is null', () => {
    expect(ensureLibraryGroupByType(null, LibraryGroupByType.Group)).toBe(LibraryGroupByType.Group);
  });

  it('should return fallback when value is undefined', () => {
    expect(ensureLibraryGroupByType(undefined, LibraryGroupByType.Series)).toBe(
      LibraryGroupByType.Series,
    );
  });

  it('should return fallback when value is invalid', () => {
    expect(ensureLibraryGroupByType('invalid', LibraryGroupByType.Group)).toBe(
      LibraryGroupByType.Group,
    );
    expect(ensureLibraryGroupByType('random', LibraryGroupByType.Author)).toBe(
      LibraryGroupByType.Author,
    );
  });

  it('should return fallback when value is empty string', () => {
    expect(ensureLibraryGroupByType('', LibraryGroupByType.Group)).toBe(LibraryGroupByType.Group);
  });
});

describe('findGroupById', () => {
  const createMockGroup = (overrides: Partial<BooksGroup> = {}): BooksGroup => ({
    id: 'test-group',
    name: 'Test Group',
    displayName: 'Test Group',
    books: [],
    updatedAt: Date.now(),
    ...overrides,
  });

  it('should find group by id', () => {
    const items: (Book | BooksGroup)[] = [
      createMockBook({ hash: '1' }),
      createMockGroup({ id: 'group-1', name: 'Group 1' }),
      createMockGroup({ id: 'group-2', name: 'Group 2' }),
    ];

    const found = findGroupById(items, 'group-2');
    expect(found).toBeDefined();
    expect(found!.name).toBe('Group 2');
  });

  it('should return undefined when group not found', () => {
    const items: (Book | BooksGroup)[] = [
      createMockBook({ hash: '1' }),
      createMockGroup({ id: 'group-1', name: 'Group 1' }),
    ];

    const found = findGroupById(items, 'non-existent');
    expect(found).toBeUndefined();
  });

  it('should not match books', () => {
    const items: (Book | BooksGroup)[] = [
      createMockBook({ hash: 'group-1' }), // Book with hash matching a group id
      createMockGroup({ id: 'group-2', name: 'Group 2' }),
    ];

    const found = findGroupById(items, 'group-1');
    expect(found).toBeUndefined();
  });
});

describe('getGroupDisplayName', () => {
  const createMockGroup = (overrides: Partial<BooksGroup> = {}): BooksGroup => ({
    id: 'test-group',
    name: 'Test Group',
    displayName: 'Test Display Name',
    books: [],
    updatedAt: Date.now(),
    ...overrides,
  });

  it('should return displayName when available', () => {
    const items: (Book | BooksGroup)[] = [
      createMockGroup({ id: 'group-1', name: 'Name', displayName: 'Display Name' }),
    ];

    expect(getGroupDisplayName(items, 'group-1')).toBe('Display Name');
  });

  it('should return name when displayName is empty', () => {
    const items: (Book | BooksGroup)[] = [
      createMockGroup({ id: 'group-1', name: 'Name', displayName: '' }),
    ];

    expect(getGroupDisplayName(items, 'group-1')).toBe('Name');
  });

  it('should return undefined when group not found', () => {
    const items: (Book | BooksGroup)[] = [createMockGroup({ id: 'group-1', name: 'Name' })];

    expect(getGroupDisplayName(items, 'non-existent')).toBeUndefined();
  });
});