File size: 56,493 Bytes
c883a41
c4ffff1
c883a41
 
 
 
 
 
 
 
 
 
 
 
94e5b7b
 
 
 
 
 
 
 
 
 
 
 
f2ca8a4
 
 
 
 
 
 
 
 
 
 
c883a41
 
 
 
 
 
 
 
 
 
5358ce3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c883a41
26ada3d
c883a41
 
 
 
 
 
 
 
 
 
 
 
 
 
f5a2dbc
c883a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e80b8a
 
 
 
 
f5a2dbc
0f41e17
 
 
 
 
 
21dd1a0
c883a41
 
 
5945064
 
 
 
 
 
 
c883a41
 
 
 
9e80b8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8fba3b
9e80b8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c883a41
 
43e916c
 
 
 
 
 
 
 
 
 
 
 
 
 
45892ca
43e916c
 
 
45892ca
43e916c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c883a41
 
5945064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0962ce
5945064
 
 
 
c883a41
 
f5a2dbc
26ada3d
c883a41
f5a2dbc
 
 
 
 
645689d
 
f5a2dbc
 
 
 
 
7bb1271
 
 
 
 
a714927
7bb1271
 
 
 
 
 
 
 
 
 
a714927
f5a2dbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
645689d
 
f5a2dbc
5945064
 
c4ffff1
f5a2dbc
 
5945064
 
645689d
5945064
ce7dbe1
645689d
 
2c1bed8
645689d
 
3a73ec8
 
 
645689d
 
0eba486
ce7dbe1
 
645689d
 
2c1bed8
645689d
 
 
ce7dbe1
 
645689d
5945064
 
 
f5a2dbc
4df129b
 
 
0eba486
 
 
 
 
 
 
 
498c7fc
 
 
 
 
 
 
 
 
 
0eba486
 
 
 
 
 
 
 
 
 
 
 
 
a3e8ceb
0eba486
 
 
645ada0
72f741b
0eba486
645ada0
a3e8ceb
72f741b
35345f5
0eba486
 
 
 
 
 
72f741b
 
0eba486
 
 
 
 
 
 
 
a3e8ceb
 
72f741b
a3e8ceb
0eba486
72f741b
 
 
 
 
 
 
 
0eba486
 
72f741b
a3e8ceb
72f741b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43e916c
 
 
 
d6bb80e
43e916c
d6bb80e
43e916c
 
 
 
 
 
d6bb80e
 
 
43e916c
 
d6bb80e
 
 
 
 
 
 
 
 
 
 
 
72f741b
d6bb80e
 
 
 
 
 
 
72f741b
d6bb80e
72f741b
d6bb80e
 
72f741b
 
 
 
 
d6bb80e
72f741b
d6bb80e
72f741b
 
 
 
 
 
 
 
d6bb80e
a3e8ceb
 
43e916c
a714927
 
 
43e916c
 
 
 
 
 
 
 
 
 
 
 
 
45892ca
43e916c
 
 
45892ca
43e916c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a714927
 
 
6f3f719
a714927
 
 
 
 
5945064
6f3f719
5945064
 
 
 
 
645689d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4ffff1
25024a8
 
 
 
f5a2dbc
 
c4ffff1
 
f5a2dbc
c4ffff1
 
 
5358ce3
f5a2dbc
 
c75bd26
c4ffff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7856be
c4ffff1
 
a359212
 
7eacb56
c4ffff1
 
 
68a6108
3b3ad2a
 
 
68a6108
3b3ad2a
c4ffff1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5358ce3
c4ffff1
 
 
 
 
f5a2dbc
 
 
 
c883a41
5358ce3
c883a41
 
f5a2dbc
 
 
 
 
 
 
 
5358ce3
f5a2dbc
 
 
 
c883a41
 
 
 
 
 
 
 
 
f5a2dbc
 
c883a41
 
 
 
 
 
fd2dd2f
4987365
f5f73d3
af9ff46
f5f73d3
 
 
 
 
 
4987365
 
 
 
 
 
 
 
 
 
 
 
c883a41
3a6fed5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ada3d
 
 
c883a41
26ada3d
f4b8495
 
c883a41
 
 
f4b8495
c883a41
 
3a6fed5
 
 
 
 
 
 
 
f5f73d3
 
 
ffac483
f5f73d3
 
 
 
3a6fed5
 
 
 
 
 
c883a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b32a81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883e14b
 
 
 
 
 
8b32a81
905b1d0
 
 
 
 
 
 
 
 
 
 
8b32a81
 
 
 
905b1d0
 
 
 
8b32a81
 
 
 
 
c883a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b02f9a1
 
 
 
 
83f3a73
b02f9a1
83f3a73
 
 
 
 
 
 
 
 
 
 
 
 
 
b02f9a1
83f3a73
b02f9a1
c883a41
 
 
 
 
 
 
 
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
import { db } from '../../db/database.js';
import { aiRouter } from '../../ai/router.js';

export class LearnView {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.decks = [];
    this.activeDeckId = null;
    this.dueCards = [];
    this.currentCardIndex = 0;
  }

  async init() {
    this.loadDecks();
    window.addEventListener('flashcards-updated', () => {
      this.loadDecks();
      // Don't interrupt if user is actively studying
      const isStudyMode = this.container.querySelector('.study-mode-container') !== null;
      if (isStudyMode) return;
      
      if (this.activeDeckId) {
        this.renderDeckDetails(this.activeDeckId);
      } else if (this.container.innerHTML.trim() !== '') {
        this.renderOverview();
      }
    });

    window.addEventListener('cloud_sync_updated', () => {
      this.loadDecks();
      const isStudyMode = this.container.querySelector('.study-mode-container') !== null;
      if (isStudyMode) return; // Don't interrupt study
      if (this.activeDeckId) {
        this.renderDeckDetails(this.activeDeckId);
      } else if (this.container.innerHTML.trim() !== '') {
        this.renderOverview();
      }
    });
  }

  loadDecks() {
    this.decks = db.getDecks();
  }

  render() {
    this.renderOverview();
  }

  appAlert(message) {
    return new Promise(resolve => {
      const overlay = document.createElement('div');
      overlay.className = 'custom-modal-overlay';
      overlay.innerHTML = `
        <div class="custom-modal">
          <h3>Hinweis</h3>
          <p>${message}</p>
          <div class="modal-actions">
            <button class="modal-btn confirm">OK</button>
          </div>
        </div>
      `;
      document.body.appendChild(overlay);
      const btn = overlay.querySelector('.confirm');
      btn.onclick = () => {
        overlay.classList.add('fade-out');
        setTimeout(() => { overlay.remove(); resolve(); }, 300);
      };
    });
  }

  renderOverview() {
    this.container.style.overflow = '';
    this.loadDecks();
    let decksHtml = '';
    
    if (this.decks.length === 0) {
      decksHtml = `
        <div style="text-align: center; color: var(--text-secondary); margin-top: 40px;">
          <div style="font-size: 40px; margin-bottom: 16px;">📚</div>
          <p>Du hast noch keine Karteikarten.</p>
        </div>
      `;
    } else {
      decksHtml = `
        <div class="decks-grid">
          ${this.decks.map(deck => `
            <div class="deck-card" onclick="window.learnView.renderDeckDetails('${deck.id}')">
              <div class="deck-icon-wrapper" style="background: ${deck.color}20; color: ${deck.color};">
                ${deck.title.charAt(0).toUpperCase()}
              </div>
              <h3 class="deck-title">${deck.title}</h3>
              <div class="deck-stats">
                <span>${deck.total_count} Karten</span>
                ${deck.due_count > 0 ? `<span class="due-badge">${deck.due_count} fällig</span>` : `<span style="color:var(--text-tertiary)">Alles erledigt</span>`}
              </div>
            </div>
          `).join('')}
        </div>
      `;
    }

    this.container.innerHTML = `
      <div class="learn-view" id="learn-scroll-container" style="height: 100%; overflow-y: auto; position: relative;">
        <div id="ptr-indicator" style="text-align: center; color: var(--text-secondary); font-size: 13px; padding: 10px; height: 0; overflow: hidden; opacity: 0; transition: height 0.2s, opacity 0.2s, padding 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px;">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>
          Ziehen zum Aktualisieren
        </div>
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
          <div style="display: flex; align-items: center; gap: 12px;">
            <button onclick="window.openView('Hub')" class="icon-btn" style="background: transparent; padding: 0; width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; color: var(--text-secondary);">
              <svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>
            </button>
            <h2 style="margin: 0; font-size: 28px; color: var(--text-primary);">Lernen</h2>
          </div>
          <button id="add-deck-btn" class="icon-btn gpu-accelerated" style="background: rgba(255,255,255,0.05); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.05); border-radius: 50%; width: 44px; height: 44px; display: flex; align-items: center; justify-content: center;">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>
          </button>
        </div>
        
        <div style="margin-bottom: 24px; position: relative;">
          <input type="text" id="global-vocab-search" placeholder="Alle Vokabeln durchsuchen..." style="width: 100%; padding: 14px 16px 14px 40px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; font-size: 16px; outline: none; box-sizing: border-box;">
          <svg style="position: absolute; left: 14px; top: 14px; color: rgba(255,255,255,0.4);" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
        </div>
        <div id="vocab-search-results" style="display: none; flex-direction: column; gap: 8px; margin-bottom: 24px;"></div>
        
        ${decksHtml}
      </div>
    `;

    // Pull-to-refresh logic
    const scrollContainer = document.getElementById('learn-scroll-container');
    const ptrIndicator = document.getElementById('ptr-indicator');
    if (scrollContainer && ptrIndicator) {
      let startY = 0;
      let currentY = 0;
      let isPulling = false;
      let threshold = 60;

      scrollContainer.addEventListener('touchstart', (e) => {
        if (scrollContainer.scrollTop === 0) {
          startY = e.touches[0].clientY;
          isPulling = true;
          ptrIndicator.style.transition = 'none';
        }
      }, { passive: true });

      scrollContainer.addEventListener('touchmove', (e) => {
        if (!isPulling) return;
        currentY = e.touches[0].clientY;
        const diff = currentY - startY;
        
        if (diff > 0 && scrollContainer.scrollTop === 0) {
          const move = Math.min(diff * 0.4, threshold + 20);
          ptrIndicator.style.height = `${move}px`;
          ptrIndicator.style.opacity = move / threshold;
          
          if (move >= threshold) {
            ptrIndicator.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/></svg> Loslassen zum Aktualisieren';
          } else {
            ptrIndicator.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M19 12l-7 7-7-7"/></svg> Ziehen zum Aktualisieren';
          }
        }
      }, { passive: true });

      scrollContainer.addEventListener('touchend', () => {
        if (!isPulling) return;
        isPulling = false;
        ptrIndicator.style.transition = 'height 0.3s, opacity 0.3s';
        
        const diff = currentY - startY;
        if (diff * 0.4 >= threshold) {
          ptrIndicator.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> Lade...';
          ptrIndicator.style.height = '40px';
          ptrIndicator.style.opacity = '1';
          
          // Trigger global background sync check manually
          document.dispatchEvent(new Event('visibilitychange'));
          
          setTimeout(() => {
            this.renderOverview();
          }, 800);
        } else {
          ptrIndicator.style.height = '0px';
          ptrIndicator.style.opacity = '0';
        }
      });
    }

    const addBtn = document.getElementById('add-deck-btn');
    if (addBtn) {
      addBtn.addEventListener('click', () => {
        const overlay = document.createElement('div');
        overlay.className = 'custom-modal-overlay';
        overlay.innerHTML = `
          <div class="custom-modal" style="width: 100%; max-width: 400px;">
            <h3 style="margin-bottom: 20px;">Neuer Stapel</h3>
            
            <div style="display: flex; flex-direction: column; gap: 16px; margin-bottom: 24px; text-align: left;">
              <div>
                <label style="display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary);">Name des Stapels</label>
                <input type="text" id="new-deck-title" placeholder="z.B. Englisch Vokabeln" style="width: 100%; padding: 14px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; outline: none; font-size: 16px; box-sizing: border-box;">
              </div>
              
              <div style="display: flex; gap: 12px;">
                <div style="flex: 1; display: flex; flex-direction: column; justify-content: flex-end;">
                  <label style="display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary);">Wort (Vorderseite)</label>
                  <input type="text" id="new-deck-source" placeholder="z.B. Englisch" value="Englisch" style="width: 100%; padding: 14px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; outline: none; font-size: 16px; box-sizing: border-box;">
                </div>
                <div style="flex: 1; display: flex; flex-direction: column; justify-content: flex-end;">
                  <label style="display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary);">Übersetzung (Rückseite)</label>
                  <input type="text" id="new-deck-target" placeholder="z.B. Deutsch" value="Deutsch" style="width: 100%; padding: 14px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; outline: none; font-size: 16px; box-sizing: border-box;">
                </div>
              </div>
            </div>
            
            <div class="modal-actions" style="display: flex; gap: 12px;">
              <button class="modal-btn cancel" style="flex: 1; background: rgba(255,255,255,0.1);">Abbrechen</button>
              <button class="modal-btn confirm" style="flex: 1; background: var(--primary);">Erstellen</button>
            </div>
          </div>
        `;
        document.body.appendChild(overlay);
        
        // Auto-focus title
        setTimeout(() => {
           const input = overlay.querySelector('#new-deck-title');
           if(input) input.focus();
        }, 100);

        overlay.querySelector('.cancel').onclick = () => {
          overlay.classList.add('fade-out');
          setTimeout(() => overlay.remove(), 300);
        };
        
        overlay.querySelector('.confirm').onclick = () => {
          const title = overlay.querySelector('#new-deck-title').value.trim();
          const source = overlay.querySelector('#new-deck-source').value.trim();
          const target = overlay.querySelector('#new-deck-target').value.trim();
          
          if (title && source && target) {
            db.createDeck(title, '', '#8a53e6', source, target);
            this.renderOverview();
            overlay.classList.add('fade-out');
            setTimeout(() => overlay.remove(), 300);
          }
        };
      });
    }

    const searchInput = document.getElementById('global-vocab-search');
    const searchResults = document.getElementById('vocab-search-results');
    if (searchInput) {
      searchInput.addEventListener('input', (e) => {
        const query = e.target.value.trim();
        if (query.length < 2) {
          searchResults.style.display = 'none';
          searchResults.innerHTML = '';
          return;
        }
        
        const results = db.searchFlashcards(query);
        if (results.length === 0) {
          searchResults.style.display = 'flex';
          searchResults.innerHTML = '<div style="padding: 16px; text-align: center; color: rgba(255,255,255,0.5); font-size: 14px; background: rgba(255,255,255,0.02); border-radius: 12px;">Keine Vokabeln gefunden.</div>';
          return;
        }
        
        searchResults.style.display = 'flex';
        searchResults.innerHTML = results.map(card => `
          <div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; padding: 12px 16px; cursor: pointer; display: flex; flex-direction: column; gap: 6px;" onclick="window.learnView.renderDeckDetails('${card.deck_id}')">
            <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 12px;">
              <div style="font-weight: 500; font-size: 15px; color: white;">${card.front}</div>
              <div style="font-size: 11px; padding: 3px 8px; border-radius: 6px; background: ${card.deck_color}20; color: ${card.deck_color}; white-space: nowrap;">${card.deck_title}</div>
            </div>
            <div style="font-size: 13px; color: rgba(255,255,255,0.6); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${(card.back || '').split('\n')[0]}</div>
          </div>
        `).join('');
      });
    }
  }

  renderDeckDetails(deckId) {
    this.container.style.overflow = '';
    this.activeDeckId = deckId;
    const deck = this.decks.find(d => d.id === deckId);
    if (!deck) return this.renderOverview();

    // Re-fetch counts
    const dueCards = db.getDueCards(deckId);
    // Fetch all cards for the list
    const allCards = db.getCardsForDeck(deckId);
    deck.due_count = dueCards.length;
    deck.total_count = allCards.length;

    this.container.innerHTML = `
      <div class="learn-view">
        <div style="position: sticky; top: -24px; z-index: 100; margin-top: -24px; margin-bottom: 24px;">
          <div style="position: absolute; top: 0; left: -24px; right: -24px; bottom: -24px; background: linear-gradient(to bottom, rgba(10,10,12,1) 60%, rgba(10,10,12,0) 100%); pointer-events: none; z-index: 0;"></div>
          <div style="display: flex; align-items: center; gap: 12px; padding: 24px 0 12px 0; position: relative; z-index: 1;">
            <button onclick="window.learnView.renderOverview()" class="icon-btn gpu-accelerated" style="background: rgba(255,255,255,0.05); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.05); border-radius: 50%; width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
            </button>
            <h2 style="margin: 0; font-size: 24px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${deck.title}</h2>
            
            <div style="display: flex; gap: 8px;">
              <button onclick="window.learnView.renameDeck('${deckId}')" class="icon-btn" style="background: rgba(255,255,255,0.05); border: none; padding: 10px; border-radius: 12px; color: var(--text-primary);" title="Umbenennen">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path></svg>
              </button>
              <button onclick="window.learnView.deleteDeck('${deckId}')" class="icon-btn" style="background: rgba(255,75,75,0.1); border: none; padding: 10px; border-radius: 12px; color: #ff4b4b;" title="Löschen">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
              </button>
            </div>
          </div>
        </div>

        <div style="background: var(--surface-1); border-radius: 20px; padding: 24px; text-align: center; margin-bottom: 24px; border: 1px solid var(--border);">
          <div style="font-size: 48px; margin-bottom: 12px;">${deck.title.charAt(0).toUpperCase()}</div>
          <p style="color: var(--text-secondary); margin-bottom: 24px;">${deck.total_count} Karten insgesamt</p>
          
          <div style="display: flex; flex-direction: column; gap: 12px;">
            <button onclick="window.learnView.startStudyDue('${deckId}')" style="padding: 16px; background: var(--primary); color: white; border: none; border-radius: 12px; font-weight: bold; font-size: 16px; cursor: pointer; display: flex; justify-content: space-between; align-items: center;">
              <span>Fällige Karten lernen</span>
              ${deck.due_count > 0 ? `<span style="background: rgba(255,255,255,0.2); padding: 4px 10px; border-radius: 20px; font-size: 14px;">${deck.due_count}</span>` : `<span style="opacity: 0.7; font-size: 14px;">Fertig</span>`}
            </button>
            <button onclick="window.learnView.startStudyAll('${deckId}')" style="padding: 16px; background: var(--surface-2); color: var(--text-primary); border: 1px solid var(--border); border-radius: 12px; font-weight: bold; font-size: 16px; cursor: pointer; display: flex; justify-content: space-between; align-items: center;">
              <span>Alle Karten frei üben</span>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg>
            </button>
          </div>
        </div>

        <h3 style="margin-bottom: 16px; font-size: 18px;">Neue Karte</h3>
        <div style="background: var(--surface-1); border-radius: 20px; padding: 20px; border: 1px solid var(--border); margin-bottom: 32px;">
          <div style="display: flex; flex-direction: column; gap: 12px;">
            <input type="text" id="new-card-front" placeholder="Vorderseite (Frage)" style="background: var(--background); border: 1px solid var(--border); color: var(--text-primary); padding: 12px; border-radius: 10px; font-size: 16px; outline: none;">
            <input type="text" id="new-card-back" placeholder="Rückseite (Antwort)" style="background: var(--background); border: 1px solid var(--border); color: var(--text-primary); padding: 12px; border-radius: 10px; font-size: 16px; outline: none;">
            <button id="add-card-btn" onclick="window.learnView.addCard('${deckId}')" style="padding: 12px; background: var(--primary); color: white; border: none; border-radius: 10px; font-weight: bold; cursor: pointer; display: flex; justify-content: center; align-items: center; gap: 8px;">Hinzufügen</button>
          </div>
        </div>

        <h3 style="margin-bottom: 16px; font-size: 18px;">Alle Karten (${deck.total_count})</h3>
        <div style="background: var(--surface-1); border-radius: 20px; border: 1px solid var(--border); padding-bottom: 1px; min-height: 100px;">
          ${deck.total_count === 0 ? '<div style="padding: 24px; text-align: center; color: var(--text-secondary);">Noch keine Karten in diesem Stapel.</div>' : `
          <div style="display: flex; flex-direction: column;">
            ${allCards.map((card, index) => {
              // Extract the first part of back for the preview (before the explanation)
              let previewBack = (card.back || '').split('\n\n**Erklärung:**')[0].trim();
              if (previewBack.length > 60) previewBack = previewBack.substring(0, 60) + '...';
              
              // Escape quotes and newlines for onclick
              const safeFront = card.front.replace(/'/g, "\\'").replace(/"/g, "&quot;").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
              const safeBack = card.back.replace(/'/g, "\\'").replace(/"/g, "&quot;").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
              
              return `
              <div onclick="window.learnView.previewCard('${card.id}', '${deckId}')" style="display: flex; justify-content: space-between; align-items: center; padding: 16px; border-bottom: ${index === deck.total_count - 1 ? 'none' : '1px solid var(--border)'}; cursor: pointer; transition: background 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.02)'" onmouseout="this.style.background='transparent'">
                <div style="flex: 1; min-width: 0; padding-right: 12px;">
                  <div style="font-weight: 500; font-size: 16px; margin-bottom: 4px; color: var(--text-primary); text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">${card.front}</div>
                  <div style="font-size: 13px; color: var(--text-secondary); text-overflow: ellipsis; overflow: hidden; white-space: nowrap;">${previewBack}</div>
                </div>
                <div style="display: flex; gap: 4px; flex-shrink: 0;" onclick="event.stopPropagation()">
                  <button onclick="window.learnView.deleteCard('${card.id}', '${deckId}')" class="icon-btn" style="background: rgba(255,75,75,0.1); color: #ff4b4b; border: none; padding: 8px; border-radius: 8px;" title="Löschen">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"></path><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>
                  </button>
                </div>
              </div>
            `}).join('')}
          </div>
          `}
        </div>
      </div>
    `;
  }

  async previewCard(cardId, deckId) {
    // Fetch fresh card data
    const res = db.exec("SELECT * FROM flashcards WHERE id = ?", [cardId]);
    if (!res || res.length === 0) return;
    const card = res[0];

    const formatBack = (text) => {
      if (!text) return '';
      let t = text;
      
      // Try to center the first line if it's the translation
      const lines = t.split(/\n/);
      if (lines.length > 0 && lines[0].trim() !== '' && !lines[0].includes('**')) {
        lines[0] = `<div class="translation-line" style="text-align: center; font-size: 26px; font-weight: 500; margin-bottom: 8px;">${lines[0]}</div>`;
        t = lines.join('\n');
      }
      
      t = t.replace(/\\n/g, '<br>');
      t = t.replace(/\n/g, '<br>');
      t = t.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
      return t;
    };

    const overlay = document.createElement('div');
    overlay.className = 'custom-modal-overlay';
    overlay.style.zIndex = '999999';
    overlay.style.backdropFilter = 'blur(10px)';
    
    // We render a standard flashcard inside the modal
    overlay.innerHTML = `
      <div style="display: flex; flex-direction: column; align-items: center; justify-content: center; width: 100%; max-width: 400px; padding: 20px;">
        <h3 style="margin-bottom: 24px; color: white; font-size: 20px; font-weight: 500;">Karten-Vorschau (Antippen zum Bearbeiten)</h3>
        
        <div class="flashcard" onclick="this.querySelector('.flashcard-inner').classList.toggle('flipped')" style="width: 100%; height: 400px; margin-bottom: 24px; cursor: pointer;">
          <div class="flashcard-inner" style="width: 100%; height: 100%; position: relative; transition: transform 0.6s; transform-style: preserve-3d;">
            <div class="flashcard-front" style="position: absolute; width: 100%; height: 100%; backface-visibility: hidden; background: var(--surface-1); border: 1px solid var(--border); border-radius: 20px; display: flex; flex-direction: column; padding: 32px; box-sizing: border-box; box-shadow: 0 10px 30px rgba(0,0,0,0.5); overflow-y: auto; overflow-x: hidden;">
              <div id="edit-front-${card.id}" contenteditable="true" spellcheck="false" onclick="event.stopPropagation()" style="font-size: 32px; font-weight: 500; text-align: center; color: white; outline: none; width: 100%; margin: auto 0; padding: 10px; border-radius: 8px; border: 1px solid transparent;" onfocus="this.style.border='1px solid rgba(255,255,255,0.2)'; this.style.background='rgba(0,0,0,0.2)'" onfocusout="this.style.border='1px solid transparent'; this.style.background='transparent'">${card.front}</div>
            </div>
            <div class="flashcard-back" style="position: absolute; width: 100%; height: 100%; backface-visibility: hidden; background: var(--surface-1); border: 1px solid var(--border); border-radius: 20px; display: flex; flex-direction: column; padding: 32px; box-sizing: border-box; box-shadow: 0 10px 30px rgba(0,0,0,0.5); transform: rotateY(180deg); overflow-y: auto; overflow-x: hidden;">
              ${card.image_url ? `<img src="${card.image_url}" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; opacity: 0.15; z-index: 0; pointer-events: none;">` : ''}
              <div id="edit-back-${card.id}" contenteditable="true" spellcheck="false" onclick="event.stopPropagation()" style="position: relative; z-index: 1; font-size: 20px; font-weight: 400; text-align: left; color: white; line-height: 1.5; outline: none; width: 100%; margin: auto 0; padding: 10px; border-radius: 8px; border: 1px solid transparent; white-space: pre-wrap;" onfocus="this.style.border='1px solid rgba(255,255,255,0.2)'; this.style.background='rgba(0,0,0,0.2)'" onfocusout="this.style.border='1px solid transparent'; this.style.background='transparent'">
                ${formatBack(card.back)}
              </div>
            </div>
          </div>
        </div>
        
        <div style="display: flex; gap: 12px; width: 100%;">
          <button class="modal-btn cancel" style="flex: 1; background: rgba(255,255,255,0.1); color: white; padding: 16px; border-radius: 14px;">Abbrechen</button>
          <button class="modal-btn save" style="flex: 1; background: var(--primary); color: white; padding: 16px; border-radius: 14px; font-weight: bold;">Speichern</button>
        </div>
      </div>
    `;
    
    document.body.appendChild(overlay);
    
    overlay.querySelector('.cancel').onclick = () => {
      overlay.classList.add('fade-out');
      setTimeout(() => {
        overlay.remove();
        this.renderDeckDetails(deckId);
      }, 300);
    };

    overlay.querySelector('.save').onclick = () => {
      const frontEl = overlay.querySelector('#edit-front-' + card.id);
      const backEl = overlay.querySelector('#edit-back-' + card.id);
      if (frontEl && backEl) {
        this.handleSaveCard(card, deckId, frontEl.innerText, backEl.innerHTML, overlay);
      }
    };
  }

  async handleSaveCard(card, deckId, newFront, htmlBack, overlay) {
    if (!newFront || newFront.trim() === '') return;
    
    let newBack = htmlBack;
    newBack = newBack.replace(/<div class="translation-line"[^>]*>(.*?)<\/div>/gi, '$1');
    newBack = newBack.replace(/<div><br><\/div>/gi, '\n');
    newBack = newBack.replace(/<div[^>]*>/gi, '\n');
    newBack = newBack.replace(/<\/div>/gi, '');
    newBack = newBack.replace(/<br\s*\/?>/gi, '\n');
    newBack = newBack.replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**');
    newBack = newBack.replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**');
    newBack = newBack.replace(/&nbsp;/g, ' ');
    newBack = newBack.replace(/&lt;/g, '<');
    newBack = newBack.replace(/&gt;/g, '>');
    newBack = newBack.replace(/&amp;/g, '&');
    
    if (card.front.trim() === newFront.trim()) {
       db.editFlashcard(card.id, newFront.trim(), newBack);
       overlay.classList.add('fade-out');
       setTimeout(() => {
         overlay.remove();
         this.renderDeckDetails(deckId);
       }, 300);
       return;
    }
    
    db.editFlashcard(card.id, newFront.trim(), newBack);
    this.renderDeckDetails(deckId);
    
    const saveBtn = overlay.querySelector('.save');
    if(saveBtn) {
       saveBtn.disabled = true;
       saveBtn.style.opacity = '0.5';
       saveBtn.innerText = 'Generiere...';
    }
    
    const backEl = overlay.querySelector('.flashcard-back');
    if (backEl) {
       const loader = document.createElement('div');
       loader.id = 'ai-regenerate-loader';
       loader.style = 'position: absolute; top:0; left:0; width:100%; height:100%; background: rgba(10,10,12,0.85); display: flex; flex-direction: column; align-items:center; justify-content:center; z-index: 10; color: var(--primary); font-weight: 500; font-size: 14px; backdrop-filter: blur(4px);';
       loader.innerHTML = `
         <style>@keyframes pulseAI { 0% { opacity:0.5; transform: scale(0.9); } 50% { opacity:1; transform: scale(1.1); } 100% { opacity:0.5; transform: scale(0.9); } }</style>
         <div style="margin-bottom: 12px; font-size: 24px; animation: pulseAI 1.5s infinite;">✨</div>
         <div>KI generiert neue Karte...</div>
       `;
       backEl.appendChild(loader);
       
       const inner = overlay.querySelector('.flashcard-inner');
       if (inner && !inner.classList.contains('flipped')) {
           inner.classList.add('flipped');
       }
    }
    
    try {
        const deck = this.decks.find(d => d.id === deckId);
        const sourceLang = deck?.source_lang || 'die jeweilige Sprache';
        const targetLang = deck?.target_lang || 'die Zielsprache';
        
        const prompt = `Du bist ein KI-Tutor. Generiere die Rückseite für eine Vokabelkarte.
Stapel-Sprachen: Wort in ${sourceLang} -> Übersetzung/Erklärung in ${targetLang}.
Wort: "${newFront.trim()}"

WICHTIGE REGELN:
1. "translation" MUSS zwingend die reine, korrekte Übersetzung in ${targetLang} sein. NICHT LEER LASSEN!
2. "explanation" MUSS in ${targetLang} sein und extrem kurz (maximal 15 Wörter!).
3. "example" MUSS ein sinnvoller Beispielsatz in ${targetLang} sein.

Gib AUSSCHLIESSLICH ein valides JSON-Objekt zurück, ohne Markdown-Formatierung wie \`\`\`json. Format:
{
  "translation": "Die kurze Übersetzung",
  "explanation": "Eine sehr kurze Erklärung",
  "example": "Ein spezifischer Beispielsatz",
  "search_query": "Ein simpler englischer Suchbegriff für ein passendes Bild"
}`;
        
        const aiResponse = await aiRouter.sendMessage(prompt, { history: [] });
        let jsonStr = aiResponse;
        if (jsonStr.includes('\`\`\`json')) {
           jsonStr = jsonStr.split('\`\`\`json')[1].split('\`\`\`')[0];
        } else if (jsonStr.includes('\`\`\`')) {
           jsonStr = jsonStr.split('\`\`\`')[1].split('\`\`\`')[0];
        }
        
        const data = JSON.parse(jsonStr.trim());
        const aiBack = `${data.translation}\n\n**Erklärung:** ${data.explanation}\n\n**Beispiel:** ${data.example}`;
        
        let newImageUrl = null;
        if (data.search_query) {
           const encodedQuery = encodeURIComponent(data.search_query + ' single photo, clear focus, high quality');
           newImageUrl = `https://tse1.mm.bing.net/th?q=${encodedQuery}&w=800&h=1000&c=7&rs=1`;
        }
        
        db.editFlashcard(card.id, newFront.trim(), aiBack);
        if (newImageUrl) {
           db.exec("UPDATE flashcards SET image_url = ? WHERE id = ?", [newImageUrl, card.id]);
        }
        
        overlay.classList.add('fade-out');
        setTimeout(() => {
          overlay.remove();
          this.renderDeckDetails(deckId);
        }, 300);
        
    } catch (e) {
        console.error("Failed to regenerate card:", e);
        const loader = overlay.querySelector('#ai-regenerate-loader');
        if (loader) loader.remove();
        
        const saveBtn = overlay.querySelector('.save');
        if (saveBtn) {
           saveBtn.disabled = false;
           saveBtn.style.opacity = '1';
           saveBtn.innerText = 'Speichern';
        }
    }
  }
  renameDeck(deckId) {
    const deck = this.decks.find(d => d.id === deckId);
    if (!deck) return;
    
    const overlay = document.createElement('div');
    overlay.className = 'custom-modal-overlay';
    overlay.innerHTML = `
      <div class="custom-modal" style="width: 100%; max-width: 400px;">
        <h3 style="margin-bottom: 20px;">Stapel bearbeiten</h3>
        
        <div style="display: flex; flex-direction: column; gap: 16px; margin-bottom: 24px; text-align: left;">
          <div>
            <label style="display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary);">Name des Stapels</label>
            <input type="text" id="edit-deck-title" value="${deck.title}" style="width: 100%; padding: 14px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; outline: none; font-size: 16px; box-sizing: border-box;">
          </div>
          
          <div style="display: flex; gap: 12px;">
            <div style="flex: 1; display: flex; flex-direction: column; justify-content: flex-end;">
              <label style="display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary);">Wort (Vorderseite)</label>
              <input type="text" id="edit-deck-source" placeholder="z.B. Englisch" value="${deck.source_lang || ''}" style="width: 100%; padding: 14px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; outline: none; font-size: 16px; box-sizing: border-box;">
            </div>
            <div style="flex: 1; display: flex; flex-direction: column; justify-content: flex-end;">
              <label style="display: block; margin-bottom: 8px; font-size: 14px; color: var(--text-secondary);">Übersetzung (Rückseite)</label>
              <input type="text" id="edit-deck-target" placeholder="z.B. Deutsch" value="${deck.target_lang || ''}" style="width: 100%; padding: 14px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; color: white; outline: none; font-size: 16px; box-sizing: border-box;">
            </div>
          </div>
        </div>
        
        <div class="modal-actions" style="display: flex; gap: 12px;">
          <button class="modal-btn cancel" style="flex: 1; background: rgba(255,255,255,0.1);">Abbrechen</button>
          <button class="modal-btn confirm" style="flex: 1; background: var(--primary);">Speichern</button>
        </div>
      </div>
    `;
    document.body.appendChild(overlay);

    overlay.querySelector('.cancel').onclick = () => {
      overlay.classList.add('fade-out');
      setTimeout(() => overlay.remove(), 300);
    };
    
    overlay.querySelector('.confirm').onclick = () => {
      const title = overlay.querySelector('#edit-deck-title').value.trim();
      const source = overlay.querySelector('#edit-deck-source').value.trim();
      const target = overlay.querySelector('#edit-deck-target').value.trim();
      
      if (title) {
        if (title !== deck.title) {
          db.updateDeckTitle(deckId, title);
        }
        db.updateDeckLanguages(deckId, source, target);
        
        this.renderDeckDetails(deckId);
        overlay.classList.add('fade-out');
        setTimeout(() => overlay.remove(), 300);
      }
    };
  }

  async deleteDeck(deckId) {
    if (await window.appConfirm("Möchtest du diesen Stapel wirklich löschen? Alle Karten darin gehen unwiderruflich verloren!")) {
      db.deleteDeck(deckId);
      this.renderOverview();
    }
  }

  async deleteCard(cardId, deckId) {
    if (await window.appConfirm("Möchtest du diese Karte wirklich löschen?")) {
      db.deleteFlashcard(cardId);
      this.renderDeckDetails(deckId);
    }
  }

  async editCard(cardId, deckId, currentFront, currentBack) {
    const newFront = await window.appPrompt("Bearbeite die Vorderseite (Frage):", currentFront);
    if (newFront === null || newFront.trim() === "") return;
    
    // We only want to edit the raw back, not the HTML/Markdown formatting that was appended (Erklärung, Beispiel) if possible.
    // But since currentBack might already contain everything, we'll let them edit the whole thing.
    // For a better UX in the future, we could split it, but for now we let them edit the text.
    let rawBack = currentBack;
    if (currentBack.includes('\\n\\n**Erklärung:**')) {
      // Just extract the raw back for simple editing if we want to be smart, but wait, if they edit it, they lose the explanation?
      // No, they might want to edit the explanation too. We just pass the whole string.
      // But prompt doesn't support multiline. We should use a custom modal for this.
    }
    
    // Custom Modal for editing
    return new Promise(resolve => {
      const overlay = document.createElement('div');
      overlay.className = 'custom-modal-overlay';
      
      const unescapedFront = currentFront.replace(/&quot;/g, '"');
      const unescapedBack = currentBack.replace(/&quot;/g, '"').replace(/\\n/g, '\n');
      
      overlay.innerHTML = `
        <div class="custom-modal" style="width: 90%; max-width: 500px;">
          <h3>Karte bearbeiten</h3>
          <div style="display: flex; flex-direction: column; gap: 12px; margin: 16px 0;">
            <label style="font-size: 13px; color: var(--text-secondary); text-align: left;">Vorderseite</label>
            <input type="text" id="edit-front" value="${unescapedFront.replace(/"/g, '&quot;')}" style="background: var(--background); border: 1px solid var(--border); color: var(--text-primary); padding: 12px; border-radius: 10px; font-size: 16px; outline: none; width: 100%; box-sizing: border-box;">
            
            <label style="font-size: 13px; color: var(--text-secondary); text-align: left; margin-top: 8px;">Rückseite</label>
            <textarea id="edit-back" style="background: var(--background); border: 1px solid var(--border); color: var(--text-primary); padding: 12px; border-radius: 10px; font-size: 14px; outline: none; width: 100%; height: 150px; resize: vertical; box-sizing: border-box; font-family: inherit;">${unescapedBack}</textarea>
          </div>
          <div class="modal-actions" style="justify-content: flex-end; gap: 12px;">
            <button class="modal-btn cancel" style="background: var(--surface-2); color: var(--text-primary);">Abbrechen</button>
            <button class="modal-btn confirm" style="background: var(--primary); color: white;">Speichern</button>
          </div>
        </div>
      `;
      document.body.appendChild(overlay);
      
      const inputFront = overlay.querySelector('#edit-front');
      const inputBack = overlay.querySelector('#edit-back');
      
      inputFront.focus();
      
      const save = () => {
        const valF = inputFront.value.trim();
        const valB = inputBack.value.trim();
        if (valF && valB) {
          db.editFlashcard(cardId, valF, valB);
          this.renderDeckDetails(deckId);
        }
        overlay.classList.add('fade-out');
        setTimeout(() => { overlay.remove(); resolve(); }, 300);
      };
      
      overlay.querySelector('.confirm').onclick = save;
      overlay.querySelector('.cancel').onclick = () => {
        overlay.classList.add('fade-out');
        setTimeout(() => { overlay.remove(); resolve(); }, 300);
      };
    });
  }

  async addCard(deckId) {
    if (document.activeElement) {
      document.activeElement.blur();
    }
    
    const frontEl = document.getElementById('new-card-front');
    const backEl = document.getElementById('new-card-back');
    const addBtn = document.getElementById('add-card-btn');
    
    const front = frontEl.value.trim();
    const originalBack = backEl.value.trim();
    
    if (!front || !originalBack) {
      this.appAlert('Bitte fülle Vorder- und Rückseite aus.');
      return;
    }
    
    // Set Loading State
    const originalBtnContent = addBtn.innerHTML;
    addBtn.innerHTML = '<span class="spinner" style="width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.3); border-top-color: white; border-radius: 50%; display: inline-block; animation: spin 1s linear infinite;"></span> Generiere Karte...';
    addBtn.disabled = true;
    addBtn.style.opacity = '0.7';

    // Inject spinner CSS if not exists
    if (!document.getElementById('spinner-css')) {
      const style = document.createElement('style');
      style.id = 'spinner-css';
      style.innerHTML = '@keyframes spin { to { transform: rotate(360deg); } }';
      document.head.appendChild(style);
    }

    try {
      const systemInstruction = `Du bist ein Flashcard-Assistent. Der User erstellt eine Karteikarte: Vorderseite = "${front}", Rückseite (Lernwort) = "${originalBack}".
Antworte AUSSCHLIESSLICH mit einem validen JSON-Objekt ohne Markdown-Block drumherum, das folgende Felder enthält:
{
  "explanation": "1-2 kurze Sätze in der Sprache des LERNWORTS ('${originalBack}'), die genau dieses Wort auf der Rückseite erklären. WICHTIG: Markiere das Lernwort (und seine Abwandlungen) IMMER fett mit HTML-Tags (z.B. <b>${originalBack}</b>).",
  "example": "Ein prägnanter Beispielsatz mit dem Lernwort ('${originalBack}'). Das Lernwort MUSS auch hier mit <b>...</b> fett markiert sein.",
  "imageQuery": "Ein präziser englischer Suchbegriff für die Bing-Bildersuche. WICHTIG: Das Bild muss GANZ OFFENSICHTLICH und EINDEUTIG zum Wort passen! Es muss so simpel und klar sein, dass man es SOFORT ohne spezielles Vorwissen erkennt. Wähle bei abstrakten Wörtern ein extrem simples, alltägliches und leicht verständliches Motiv statt komplexer Kunst oder Metaphern. Das Motiv muss im Zentrum stehen. Füge IMMER 'single photo, clear focus, high quality' am Ende hinzu. ABSOLUT VERBOTEN: Grafiken, Text, Collagen, Cartoons. (Beispiel für 'Hund': 'a cute dog sitting on grass single photo clear focus', Beispiel für 'Zeit': 'a classic alarm clock single photo clear focus')."
}`;

      // We send a short empty prompt because the instruction handles everything
      // Wir nutzen Llama 3.3 70B über Groq als Sweetspot für Kompetenz und Geschwindigkeit
      const responseStr = await aiRouter.sendMessage("Generate JSON", { 
        systemInstruction, 
        extendedThinking: false,
        model: 'groq-llama-3.3-70b-versatile' 
      });
      
      // Parse JSON
      let data;
      try {
        const jsonMatch = responseStr.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          data = JSON.parse(jsonMatch[0]);
        } else {
          data = JSON.parse(responseStr);
        }
      } catch (e) {
        console.error("AI JSON Parse Error:", e, responseStr);
        data = { 
          explanation: "Fehler bei der KI-Generierung.", 
          example: "Bitte manuell prüfen.", 
          imageQuery: encodeURIComponent(front) 
        };
      }

      const back = `${originalBack}\n\n**Erklärung:** ${data.explanation}\n\n**Beispiel:** ${data.example}`;
      const searchTerms = encodeURIComponent(data.imageQuery);
      const imageUrl = `https://tse1.mm.bing.net/th?q=${searchTerms}&w=800&h=1000&c=7&rs=1`;
      
      db.addFlashcard(deckId, front, back, imageUrl);
      
      // Clear inputs
      frontEl.value = '';
      backEl.value = '';
      
      this.renderDeckDetails(deckId); // Refresh stats
      
    } catch (e) {
      console.error(e);
      this.appAlert('Fehler beim KI-Aufruf: ' + e.message);
      // Restore button
      addBtn.innerHTML = originalBtnContent;
      addBtn.disabled = false;
      addBtn.style.opacity = '1';
    }
  }

  startStudyDue(deckId) {
    this.dueCards = db.getDueCards(deckId);
    if (this.dueCards.length === 0) {
      this.appAlert('Für heute hast du alle Karten in diesem Stapel gelernt!');
      return;
    }
    this.isFreePractice = false;
    this.currentCardIndex = 0;
    this.renderStudyMode();
  }

  startStudyAll(deckId) {
    this.dueCards = db.getAllCards(deckId);
    if (this.dueCards.length === 0) {
      this.appAlert('Dieser Stapel ist noch leer.');
      return;
    }
    this.isFreePractice = true;
    this.currentCardIndex = 0;
    this.renderStudyMode();
  }

  renderStudyMode() {
    if (this.currentCardIndex >= this.dueCards.length) {
      this.container.innerHTML = `
        <div class="learn-view" style="align-items: center; justify-content: center;">
          <div style="font-size: 60px; margin-bottom: 20px;">🎉</div>
          <h2 style="margin: 0 0 10px 0;">Stapel abgeschlossen!</h2>
          <p style="color: var(--text-secondary); margin-bottom: 30px;">Du hast alle anstehenden Karten gelernt.</p>
          <button onclick="window.learnView.renderDeckDetails('${this.activeDeckId}')" style="padding: 12px 24px; background: var(--primary); border-radius: 20px; color: white; border: none; font-weight: 600; cursor: pointer;">Zurück zum Stapel</button>
        </div>
      `;
      return;
    }

    const card = this.dueCards[this.currentCardIndex];
    const hasImage = !!card.image_url && card.image_url !== 'null';
    
    const deck = db.exec("SELECT * FROM flashcard_decks WHERE id = ?", [this.activeDeckId])[0];
    const deckName = (deck && deck.title) ? deck.title.toLowerCase() : '';
    let lang = 'en-US';
    if (deckName.includes('spanisch') || deckName.includes('spanish')) lang = 'es-ES';
    else if (deckName.includes('französisch') || deckName.includes('french')) lang = 'fr-FR';
    else if (deckName.includes('italienisch') || deckName.includes('italian')) lang = 'it-IT';
    else if (deckName.includes('deutsch') || deckName.includes('german')) lang = 'de-DE';
    
    let backgroundHtml = '';
    let overlayHtml = '';
    
    if (hasImage) {
      backgroundHtml = `<img src="${card.image_url}" class="flashcard-image" alt="Background">`;
      overlayHtml = `<div class="flashcard-blur-overlay"></div>`;
    } else {
      // Elegant placeholder for cards without an image
      backgroundHtml = `<div class="flashcard-image" style="background: linear-gradient(135deg, #8a53e6 0%, #4a148c 100%); opacity: 0.6;"></div>`;
      // Still need a slight dark gradient at the bottom for text readability, but no blur
      overlayHtml = `<div class="flashcard-blur-overlay" style="backdrop-filter: none; -webkit-backdrop-filter: none; mask-image: none; -webkit-mask-image: none;"></div>`;
    }

    const cardsLeft = this.dueCards.length - this.currentCardIndex - 1;
    let stackHtml = '';
    if (cardsLeft > 1) {
      stackHtml += `
        <div class="flashcard-wrapper stacked-2">
          <div class="flashcard-inner">
            <div class="flashcard-face"></div>
          </div>
        </div>
      `;
    }
    if (cardsLeft > 0) {
      stackHtml += `
        <div class="flashcard-wrapper stacked-1">
          <div class="flashcard-inner">
            <div class="flashcard-face"></div>
          </div>
        </div>
      `;
    }

    // Disable scrolling globally for study mode
    this.container.style.overflow = 'hidden';
    
    this.container.innerHTML = `
      <div class="learn-view study-container" style="height: 100%; display: flex; flex-direction: column; overflow: hidden; box-sizing: border-box;">
        <div style="width: 100%; max-width: 380px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; padding: 0 16px;">
          <button onclick="window.learnView.renderDeckDetails('${this.activeDeckId}')" class="icon-btn gpu-accelerated" style="background: rgba(255,255,255,0.05); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(255,255,255,0.05); border-radius: 50%; width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
          </button>
          <span style="color: var(--text-secondary); font-weight: 600;">${this.currentCardIndex + 1} / ${this.dueCards.length}</span>
          <div style="width: 44px;"></div>
        </div>

        <div class="flashcard-stack">
          ${stackHtml}
          <div class="flashcard-wrapper current" id="current-flashcard">
            <div class="flashcard-inner">
              <!-- Front of the card (Progressive Blur UI) -->
              <div class="flashcard-face">
                ${backgroundHtml}
                ${overlayHtml}
                <div class="flashcard-content" style="width: 100%; box-sizing: border-box;">
                  <div style="display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%;">
                    <h2 class="flashcard-title" style="flex: 1; word-break: break-word;">${card.front}</h2>
                    <button class="icon-btn gpu-accelerated" onclick="event.stopPropagation(); if (window.TextToSpeech) { window.TextToSpeech.stop().catch(()=>{}); window.TextToSpeech.speak({text: '${card.front.replace(/'/g, "\\'").replace(/"/g, "&quot;")}', lang: '${lang}', rate: 1.0}).catch(e=>console.error(e)); } else { console.warn('TTS not available'); }" style="background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border: 1px solid rgba(255,255,255,0.3); border-radius: 50%; width: 44px; height: 44px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; color: white; cursor: pointer;">
                      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path><path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path></svg>
                    </button>
                  </div>
                  <p class="flashcard-subtitle" style="margin-top: 8px;">Tippe auf die Karte, um die Antwort zu sehen.</p>
                </div>
              </div>
              
              <!-- Back of the card -->
              <div class="flashcard-face flashcard-back" id="flashcard-back-content">
                <!-- Content injected via JS -->
              </div>
            </div>
          </div>
        </div>

        <div class="feedback-controls" id="feedback-controls">
          <button class="btn-feedback btn-again" onclick="window.learnView.handleFeedback(0)">
            Nochmal
            <span class="feedback-time"><1m</span>
          </button>
          <button class="btn-feedback btn-hard" onclick="window.learnView.handleFeedback(1)">
            Schwer
            <span class="feedback-time">1d</span>
          </button>
          <button class="btn-feedback btn-good" onclick="window.learnView.handleFeedback(2)">
            Gut
            <span class="feedback-time">2d</span>
          </button>
          <button class="btn-feedback btn-easy" onclick="window.learnView.handleFeedback(3)">
            Leicht
            <span class="feedback-time">4d</span>
          </button>
        </div>
      </div>
    `;

    // Parse the back content for AI generated fields
    const backContentEl = document.getElementById('flashcard-back-content');
    let formattedBack = card.back || "";
    
    let htmlContent = '';
    if (formattedBack.includes('**Erklärung:**')) {
      const parts = formattedBack.split('**Erklärung:**');
      const translation = parts[0].trim();
      let rest = parts[1];
      
      let examplePart = '';
      if (rest.includes('**Beispiel:**')) {
        const subParts = rest.split('**Beispiel:**');
        rest = subParts[0].trim();
        examplePart = subParts[1].trim();
      } else {
        rest = rest.trim();
      }
      
      // Parse markdown bold
      const parseBold = (str) => str ? str.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') : '';
      const parsedTranslation = parseBold(translation);
      const parsedRest = parseBold(rest);
      const parsedExample = parseBold(examplePart);
      
      htmlContent = `
        <div style="margin: auto 0; width: 100%; display: flex; flex-direction: column; align-items: center; box-sizing: border-box;">
          <div style="font-size: 26px; font-weight: bold; color: var(--text-primary); text-align: center; margin-bottom: 24px;">${parsedTranslation}</div>
          <div style="text-align: left; width: 100%; padding: 16px; background: rgba(0,0,0,0.3); border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); font-size: 14px; line-height: 1.5; color: rgba(255,255,255,0.85); margin-bottom: 24px; box-shadow: inset 0 2px 10px rgba(0,0,0,0.2); box-sizing: border-box;">
            <div style="color: var(--primary); font-weight: bold; font-size: 11px; text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 6px;">Erklärung</div>
            <div style="margin-bottom: 16px;">${parsedRest}</div>
            ${parsedExample ? `
              <div style="color: var(--primary); font-weight: bold; font-size: 11px; text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 6px;">Beispiel</div>
              <div><i>"${parsedExample}"</i></div>
            ` : ''}
          </div>
          <div style="font-size: 14px; color: var(--text-secondary); text-align: center;">Bewerte nun, wie gut du die Antwort wusstest.</div>
        </div>
      `;
    } else {
      htmlContent = `
        <div style="margin: auto 0; width: 100%; display: flex; flex-direction: column; align-items: center; box-sizing: border-box;">
          <div style="font-size: 24px; font-weight: bold; color: var(--text-primary); text-align: center; margin-bottom: 24px;">${formattedBack}</div>
          <div style="font-size: 14px; color: var(--text-secondary); text-align: center;">Bewerte nun, wie gut du die Antwort wusstest.</div>
        </div>
      `;
    }
    
    backContentEl.innerHTML = htmlContent;

    const cardEl = document.getElementById('current-flashcard');
    const innerEl = cardEl.querySelector('.flashcard-inner');
    const controls = document.getElementById('feedback-controls');
    
    let isFlipped = false;
    
    cardEl.addEventListener('click', () => {
      if (!isFlipped) {
        innerEl.classList.add('flipped');
        controls.classList.add('visible');
        isFlipped = true;
      }
    });
  }

  handleFeedback(quality) {
    const card = this.dueCards[this.currentCardIndex];
    
    if (!this.isFreePractice) {
      db.updateCardProgress(card.id, quality);
    }
    
    // Anki Intra-Session Learning Steps
    if (quality === 0) {
      // Nochmal: Direkt als nächste Karte
      card.hasBeenGood = false;
      this.dueCards.splice(this.currentCardIndex + 1, 0, card);
    } else if (quality === 1) {
      // Schwer: Nach den nächsten 3 Karten einreihen
      this.dueCards.splice(this.currentCardIndex + 4, 0, card);
    } else if (quality === 2) {
      // Gut: Bei NEUEN Karten nach 10 Karten nochmal abfragen (wie der 10-Minuten Schritt in Anki)
      // Bei Wiederholungskarten (repetitions > 0) oder wenn schonmal 'Gut' geklickt wurde -> fertig für heute!
      const isReviewCard = card.repetitions > 0;
      if (!isReviewCard && !card.hasBeenGood) {
        card.hasBeenGood = true;
        this.dueCards.splice(this.currentCardIndex + 11, 0, card);
      }
    }
    // quality === 3 (Leicht) fliegt immer sofort aus dem aktuellen Durchgang raus.
    
    this.currentCardIndex++;
    this.renderStudyMode();
  }

  destroy() {
    this.container.innerHTML = '';
  }
}