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9f5e
 
 
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
daa9f5e
 
4a58e48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1876f7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
import './style.css';
import { Engine, NATURAL_VOICES, synth, type Voice, type ModelState } from './engine';
import { parseFile, ParseError } from './parse';
import { deleteBook, getBook, kvGet, kvSet, listBooks, saveBook, updateProgress, type Book } from './db';
import { formatDuration, guessLanguage } from './text';
import SAMPLE_AUDIO from './sample-audio.json';
import { SAMPLE } from './sample';
import { PRO, FREE_MINUTES, addTrial, counts, grantBonus, isPro, mayListen, noteGate, paywallOn, recheck, savedLicense, storeLicense, trialLeft, trialUsed, verifyKey } from './pro';

const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const el = <K extends keyof HTMLElementTagNameMap>(tag: K, cls?: string, text?: string) => {
  const e = document.createElement(tag);
  if (cls) e.className = cls;
  if (text !== undefined) e.textContent = text;
  return e;
};

const SPEEDS = [0.8, 1, 1.2, 1.5, 1.75, 2];
const PLAY_PATH = 'M8 5v14l11-7z';
const PAUSE_PATH = 'M7 5h4v14H7zm6 0h4v14h-4z';
const TRASH_SVG = '<svg class="ic sm2" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3h6l1 2h4v2H4V5h4zm-3 6h12l-1 12H7z"/></svg>';
const MODEL_BYTES = 166_000_000; // fp16 model + tokenizer + one voice

let current: Book | null = null;
let sentenceEls: HTMLElement[] = [];
let chapterOffset = 0; // characters in chapters before the current one
let sentenceOffsets: number[] = [];
let modelEverReady = false;
let saveTimer: number | undefined;

const engine = new Engine({
  onSentence(chapter, index) {
    if (!current) return;
    if (chapter !== renderedChapter) renderChapter();
    highlight(index);
    updateProgressUi();
    clearTimeout(saveTimer);
    saveTimer = window.setTimeout(saveNow, 250);
    if (sleepLeft) renderSleep(); // a timed sleep also checks at every sentence (timers are throttled when hidden)
  },
  onPlaying(p) {
    sleepRun(p);
    meterTick();
    if (p && counts(current) && trialLeft() < 120) audioCtx(); // created inside a tap, so the end-of-trial sound may play
    $('play-path').setAttribute('d', p ? PAUSE_PATH : PLAY_PATH);
    $('play').setAttribute('aria-label', p ? 'Pause' : 'Play');
    if ('mediaSession' in navigator) navigator.mediaSession.playbackState = p ? 'playing' : 'paused';
    void keepAwake(p);
    if (p) firstPlayTip();
    if (!p) saveTrial();
    if (!p) saveNow();
  },
  onSleep() {
    sleepEnded();
  },
  onLimit(midway) {
    // the free minutes are used up: a soft sound when it stops a listening stretch, then the offer
    saveNow();
    if (midway) chime();
    noteGate();
    openPaywall('limit');
  },
  onBuffering(b) {
    buffering = b;
    meterTick();
    $('play').classList.toggle('buffering', b);
  },
  onModel(m) {
    renderModel(m);
  },
  onPrepare(done, total) {
    renderPrepare(done, total);
  },
  onChapterEnd(next) {
    if (next === null) {
      toast('The end. You finished this book ✓');
      saveNow();
      updateProgressUi();
    }
    else toast(`Chapter done ✓  Next: ${current?.chapters[next].title ?? ''}`);
  },
  onError(msg, code) {
    if (code === 'device-unavailable' && current) {
      if (current.lang === 'en') {
        toast('Reading with Heart, the natural voice');
        pendingAutoSwitch = false;
        engine.setVoice({ kind: 'natural', id: 'af_heart' });
        updateVoiceLabel();
        engine.play();
        return;
      }
      toast('This phone or computer has no voice for this language. Try Chrome, or add voices in your device settings.', true);
      return;
    }
    toast(msg, true);
  },
});

engine.mayContinue = () => {
  meterTick(true);
  return mayListen(current);
};
// the sample ships its sentences already read by Heart: the first thing a visitor hears is the natural voice,
// before (and without) the 160 MB download
engine.preclip = (key, chapter, i, text) => {
  if (!canOgg || current?.format !== 'sample' || key.split('|')[3] !== SAMPLE_AUDIO.voice) return undefined;
  if (SAMPLE_AUDIO.chapters[chapter]?.[i] !== text) return undefined; // sample text changed: the model reads it
  return fetch(`./sample-audio/s-${chapter}-${i}.ogg`).then((r) => (r.ok ? r.blob() : Promise.reject(new Error(String(r.status)))));
};
/** A natural voice chosen in the sample that needs the download first (Heart reads meanwhile). */
let pendingSampleVoice: Voice | null = null;
const voiceName = (id: string) => NATURAL_VOICES.find((v) => v.id === id)?.label.split(' ·')[0] || 'This voice';
/** Ogg/Opus clips (the sample and the previews) only where the browser can play them. */
const canOgg = typeof Audio !== 'undefined' && !!new Audio().canPlayType('audio/ogg; codecs=opus');
/** The sample can play the natural voice from its own clips while the model is not on this device. */
function samplePrerendered(b: Book) {
  return canOgg && b.format === 'sample' && !modelEverReady && engine.model.s !== 'ready';
}

/* ---------- free listening meter (real playback time, any voice; the sample is not counted) ---------- */
let buffering = false;
let meterFrom = 0; // when the current counted stretch started (0 = not counting)
function chipShown() {
  try {
    return !!localStorage.getItem('earshelf.chip');
  } catch {
    return true;
  }
}
/** atSentence: called at a sentence boundary (a long sentence really was heard); otherwise a 1 s timer tick. */
function meterTick(atSentence = false) {
  const now = Date.now();
  if (meterFrom) {
    const gap = (now - meterFrom) / 1000;
    // a timer tick after a long gap means the page was frozen (screen locked, laptop asleep): nobody heard that
    addTrial(gap > 3 && !atSentence ? 0 : Math.min(30, gap));
  }
  meterFrom = engine.playing && !buffering && counts(current) ? now : 0;
  if (meterFrom && !chipShown() && trialLeft() > 0 && trialLeft() <= 60) {
    try {
      localStorage.setItem('earshelf.chip', '1'); // once per device
    } catch {
      /* storage blocked */
    }
    toast('1 minute of free listening left · your place is saved');
  }
}
window.setInterval(meterTick, 1000);
let trialSaved = 0;
function saveTrial() {
  const v = trialUsed();
  if (v !== trialSaved) (trialSaved = v), void kvSet('trial', v); // a second copy, so clearing one store is not enough
}
window.setInterval(saveTrial, 10_000);
const trialRestored = kvGet<number>('trial')
  .then((v) => {
    if (typeof v === 'number' && v > trialUsed()) addTrial(0, v);
  })
  .catch(() => {});

/* ---------- end-of-trial sound: a soft rising major third (G4 → B4), well under the voice ---------- */
let actx: AudioContext | null = null;
function audioCtx() {
  try {
    actx ||= new AudioContext();
    if (actx.state === 'suspended') void actx.resume();
  } catch {
    /* no Web Audio */
  }
  return actx;
}
let chimes = 0;
function chime() {
  chimes++;
  const c = audioCtx();
  if (!c) return;
  const t0 = c.currentTime + 0.2; // a beat of silence after the last word
  [392, 493.88].forEach((f, i) => {
    const o = c.createOscillator();
    const g = c.createGain();
    o.type = 'sine';
    o.frequency.value = f;
    const t = t0 + i * 0.18;
    g.gain.setValueAtTime(0, t);
    g.gain.linearRampToValueAtTime(0.09, t + 0.015);
    g.gain.exponentialRampToValueAtTime(0.0005, t + 0.42);
    o.connect(g).connect(c.destination);
    o.start(t);
    o.stop(t + 0.45);
  });
}

function saveNow() {
  clearTimeout(saveTimer);
  if (!current) return;
  const done = engine.finished ? current.totalChars : doneChars();
  // localStorage is synchronous, so it survives a reload or tab close; IndexedDB may not finish in time
  try {
    localStorage.setItem('earshelf.pos.' + current.id, JSON.stringify({ c: engine.chapter, s: engine.index, d: done, t: Date.now() }));
  } catch {
    /* storage full or blocked */
  }
  void updateProgress(current.id, engine.chapter, engine.index, done);
}

/** Apply a newer position saved synchronously at unload, if IndexedDB missed it. */
function applyLocalPosition(b: Book) {
  try {
    const raw = localStorage.getItem('earshelf.pos.' + b.id);
    if (!raw) return;
    const pos = JSON.parse(raw);
    if (pos.t >= b.opened - 1000 && pos.c < b.chapters.length) {
      b.chapter = pos.c;
      b.sentence = pos.s;
      b.doneChars = pos.d;
    }
  } catch {
    /* ignore */
  }
}

/* ================= library ================= */
const coverUrls: string[] = [];
async function renderLibrary() {
  const books = await listBooks();
  const ul = $('books');
  ul.textContent = '';
  coverUrls.splice(0).forEach((u) => URL.revokeObjectURL(u));
  $('shelf-title').hidden = books.length === 0;
  $('library').classList.toggle('has-books', books.length > 0);
  books.forEach(applyLocalPosition);
  renderContinue(books.find((b) => !b.totalChars || b.doneChars < b.totalChars));
  $('sample').hidden = books.some((b) => b.format === 'sample');
  for (const b of books) {
    applyLocalPosition(b);
    const li = el('li', 'book');
    li.dataset.id = b.id;
    const open = el('button', 'book-open');
    open.setAttribute('aria-label', `Open ${b.title}`);
    let cover: HTMLElement;
    if (b.cover) {
      const img = el('img', 'cover') as HTMLImageElement;
      img.alt = '';
      img.src = URL.createObjectURL(b.cover);
      coverUrls.push(img.src);
      cover = img;
    } else cover = el('div', 'cover', (b.title.trim()[0] || '?').toUpperCase());
    const meta = el('div', 'book-meta');
    meta.append(el('div', 'book-title', b.title));
    const pct = b.totalChars ? Math.min(100, Math.round((b.doneChars / b.totalChars) * 100)) : 0;
    const totalMin = Math.max(1, Math.round(b.totalChars / 900));
    const leftMin = Math.max(1, Math.round(((b.totalChars - b.doneChars) / b.totalChars) * totalMin));
    const progress = pct >= 100 ? 'Finished ✓' : pct === 0 ? `${formatDuration(totalMin)} listen` : `${pct}% · ${formatDuration(leftMin)} left`;
    const sub = [b.author, progress].filter(Boolean).join(' · ');
    meta.append(el('div', 'book-sub', sub));
    const bar = el('div', 'mini-bar');
    const fill = el('div');
    fill.style.width = pct + '%';
    bar.append(fill);
    meta.append(bar);
    open.append(cover, meta);
    open.addEventListener('click', () => void openBook(b.id));

    const del = el('button', 'del');
    del.innerHTML = TRASH_SVG;
    del.setAttribute('aria-label', `Delete ${b.title}`);
    let armTimer: number | undefined;
    del.addEventListener('click', async (e) => {
      e.stopPropagation();
      if (!del.classList.contains('armed')) {
        del.classList.add('armed');
        del.textContent = 'Delete?';
        del.setAttribute('aria-label', `Confirm: delete ${b.title}`);
        armTimer = window.setTimeout(() => {
          del.classList.remove('armed');
          del.innerHTML = TRASH_SVG;
          del.setAttribute('aria-label', `Delete ${b.title}`);
        }, 3000);
        return;
      }
      clearTimeout(armTimer);
      const idx = [...ul.children].indexOf(li);
      await deleteBook(b.id);
      toast('Book removed');
      await renderLibrary();
      // keep keyboard focus nearby instead of dropping it to the page
      const next = ul.children[Math.min(idx, ul.children.length - 1)]?.querySelector<HTMLElement>('.book-open');
      requestAnimationFrame(() => (next || $('file')).focus());
    });
    li.append(open, del);
    ul.append(li);
  }
  const line = books.length ? `${books.length} book${books.length === 1 ? '' : 's'} on this phone or computer` : '';
  $('storage').textContent = line;
}

/** The most recent unfinished book, one tap from playing again. */
function renderContinue(b: Book | undefined) {
  const box = $('continue');
  box.textContent = '';
  const pct = b && b.totalChars ? Math.round((b.doneChars / b.totalChars) * 100) : 0;
  if (!b || pct >= 100) {
    box.hidden = true;
    return;
  }
  const ch = b.chapters[Math.min(b.chapter, b.chapters.length - 1)];
  const info = el('div', 'continue-info');
  const leftMin = Math.max(1, Math.round((b.totalChars - b.doneChars) / 900));
  const where = b.chapters.length > 1 ? `Chapter ${Math.min(b.chapter, b.chapters.length - 1) + 1} of ${b.chapters.length} · ` : '';
  info.append(
    el('div', 'continue-kicker', pct > 0 ? 'Continue listening' : 'Start listening'),
    el('div', 'continue-title', b.title),
    el('div', 'continue-sub', `${where}${ch?.title ?? ''}`),
    el('div', 'continue-sub', pct > 0 ? `${pct}% · ${formatDuration(leftMin)} left` : `${formatDuration(leftMin)} listen`),
  );
  const play = el('button', 'continue-play');
  play.setAttribute('aria-label', `Play ${b.title}`);
  play.innerHTML = `<svg class="ic" viewBox="0 0 24 24" aria-hidden="true"><path d="${PLAY_PATH}"/></svg>`;
  play.addEventListener('click', () => void openBook(b.id, true));
  box.append(info, play);
  box.hidden = false;
}

/** A failed file stays explained on the library until the next good file or Dismiss (a toast fades). */
function showLibError(msgs: string[]) {
  $('lib-error').hidden = msgs.length === 0;
  $('lib-error-text').textContent = msgs.join(' ');
}

async function addFiles(files: FileList | File[]) {
  const list = Array.from(files);
  if (!list.length) return;
  let lastId = '';
  openNote = null;
  const errors: string[] = [];
  showLibError([]);
  for (const f of list) {
    busy(`Opening “${f.name}”…`, 0);
    try {
      const parsed = await parseFile(f, (p) => busy(`Opening “${f.name}”…`, p)); // the bar shows progress; the live text stays quiet
      const all = parsed.chapters.map((c) => c.text).join(' ');
      const dup = (await listBooks()).find((x) => x.title === parsed.title && x.totalChars === all.length);
      if (dup) {
        openNote = { id: dup.id, text: 'Already on your shelf' };
        lastId = dup.id;
        continue;
      }
      const book: Book = {
        id: crypto.randomUUID?.() || String(Date.now() + Math.random()),
        title: parsed.title,
        author: parsed.author,
        format: parsed.format,
        lang: guessLanguage(all),
        cover: parsed.cover,
        chapters: parsed.chapters,
        added: Date.now(),
        opened: Date.now(),
        chapter: 0,
        sentence: 0,
        totalChars: all.length,
        doneChars: 0,
      };
      await saveBook(book);
      lastId = book.id;
    } catch (e) {
      busy(null);
      const msg = e instanceof ParseError ? e.message : `Could not read “${f.name}”.`;
      errors.push(msg);
      errUntil = Date.now() + 5000; // keep tips away while the card is fresh
      if (!(e instanceof ParseError)) console.error(e);
    }
  }
  busy(null);
  if (navigator.storage?.persist) void navigator.storage.persist();
  if (lastId) await openBook(lastId, true);
  else void renderLibrary();
  showLibError(errors); // also after opening a good book, so going back still explains the bad one
}

async function addSample() {
  const book: Book = {
    id: 'sample-alice',
    title: SAMPLE.title,
    author: SAMPLE.author,
    format: 'sample',
    lang: 'en',
    chapters: SAMPLE.chapters,
    added: Date.now(),
    opened: Date.now(),
    chapter: 0,
    sentence: 0,
    totalChars: SAMPLE.chapters.map((c) => c.text).join(' ').length,
    doneChars: 0,
  };
  await saveBook(book);
  await openBook(book.id, true);
}

/* ================= player ================= */
let renderedChapter = -1;

// a message from the library for one book, shown once that book is open
let openNote: { id: string; text: string } | null = null;
async function openBook(id: string, autoplay = false) {
  const b = await getBook(id);
  if (!b) return;
  applyLocalPosition(b);
  $('toast').classList.remove('show'); // a message from the library does not follow into the player
  b.opened = Date.now();
  void saveBook(b);
  // settings first, so a quick tap after the player appears is never overwritten
  const voice = await chooseVoice(b);
  const speed = (await kvGet<number>('speed')) || 1;
  current = b;
  renderedChapter = -1;
  engine.voice = voice;
  engine.setSpeed(speed);
  updateVoiceLabel();
  updateSpeedLabel();
  $('library').hidden = true;
  $('player').hidden = false;
  $('p-title').textContent = b.title;
  if (engine.artwork) URL.revokeObjectURL(engine.artwork);
  engine.artwork = b.cover ? URL.createObjectURL(b.cover) : '';
  if (location.hash !== '#book=' + id) history.pushState({ book: id }, '', '#book=' + id);
  engine.open(b, Math.min(b.chapter, b.chapters.length - 1), b.sentence);
  if (b.totalChars && b.doneChars >= b.totalChars) {
    engine.finished = true; // a finished book: show it, and Play starts over
    updateProgressUi();
  }
  if (samplePrerendered(b) && engine.voice.kind === 'natural') {
    // the sample's own clips play: no 160 MB download just for trying it (a real book starts it)
  } else if (engine.voice.kind === 'natural') engine.ensureModel();
  else maybeWarmNatural(b);
  const notes = [openNote?.id === id ? openNote.text : ''];
  openNote = null;
  if ((b.chapter > 0 || b.sentence > 0) && !engine.finished) {
    notes.push(`picked up where you left off${b.chapters.length > 1 ? ` · chapter ${engine.chapter + 1}` : ''}`);
  }
  const note = notes.filter(Boolean).join(' · ');
  if (note) toast(note[0].toUpperCase() + note.slice(1));
  if (autoplay) {
    // first win: start talking right away (a user gesture is still active)
    engine.play();
  }
}

/** Natural voice when it is ready (or downloading) and the book is English; device voice otherwise. */
async function chooseVoice(b: Book): Promise<Voice> {
  const saved = await kvGet<Voice>('voice');
  modelEverReady = !!(await kvGet<boolean>('modelReady'));
  const english = b.lang === 'en';
  if (saved?.kind === 'device') {
    // a saved device voice only applies to books in its language
    const sv = synth?.getVoices().find((v) => v.voiceURI === saved.id);
    if (sv && b.lang !== 'und' && sv.lang.toLowerCase().startsWith(b.lang)) return saved;
    if (!english) return { kind: 'device', id: pickDeviceVoice(b.lang)?.voiceURI || '' };
    if (!sv) return saved;
  }
  if (english && (modelEverReady || engine.model.s === 'ready')) return saved?.kind === 'natural' ? saved : { kind: 'natural', id: 'af_heart' };
  if (english && b.format === 'sample' && saved?.kind !== 'device') return { kind: 'natural', id: SAMPLE_AUDIO.voice };
  return { kind: 'device', id: pickDeviceVoice(b.lang)?.voiceURI || '' };
}

/** While the device voice reads, download the natural voice in the background and switch when ready. */
function maybeWarmNatural(b: Book) {
  if (b.lang !== 'en' || engine.model.s === 'loading' || engine.model.s === 'ready') return;
  void kvGet<Voice>('voice').then((saved) => {
    if (saved?.kind === 'device') return; // the user picked the device voice on purpose
    try {
      if (localStorage.getItem('earshelf.noWarm')) return; // tests
    } catch {
      /* ignore */
    }
    pendingAutoSwitch = true;
    if (metered()) offerDownload();
    else engine.ensureModel();
  });
}
function metered(): boolean {
  const c = (navigator as any).connection;
  if (!c) return false;
  return !!c.saveData || c.type === 'cellular' || /(^|-)2g|3g/.test(c.effectiveType || '');
}
function offerDownload() {
  const b = $('model-banner');
  b.classList.remove('chip');
  b.textContent = '';
  const lead = pendingSampleVoice ? `${voiceName(pendingSampleVoice.id)} needs a one-time download, then every natural voice works without internet.` : 'Want the natural voice? It needs a one-time download, then it works without internet.';
  b.append(el('div', '', `${lead} It's a big download and you seem to be on mobile data, so Wi-Fi is better.`));
  const btn = el('button', 'pill-btn', 'Download it now');
  btn.style.marginTop = '8px';
  btn.addEventListener('click', () => engine.ensureModel());
  b.append(btn);
  b.hidden = false;
}
let pendingAutoSwitch = false;

function pickDeviceVoice(lang: string): SpeechSynthesisVoice | undefined {
  const vs = (synth?.getVoices() || []).filter((v) => lang !== 'und' && v.lang.toLowerCase().startsWith(lang));
  if (!vs.length) return undefined; // unknown language: the browser picks its default voice
  // prefer the user's own locales in order (en-CA, then en-GB…), then US English, then the system default
  const norm = (l: string) => l.toLowerCase().replace('_', '-');
  const wanted = [...navigator.languages.map(norm).filter((l) => l.startsWith(lang) && l.includes('-')), lang === 'en' ? 'en-us' : ''];
  for (const w of wanted) {
    const hit = vs.find((v) => norm(v.lang) === w && v.localService) || vs.find((v) => norm(v.lang) === w);
    if (hit) return hit;
  }
  return vs.find((v) => v.default) || vs.find((v) => v.localService) || vs[0];
}

function renderChapter() {
  if (!current) return;
  renderedChapter = engine.chapter;
  const ch = current.chapters[engine.chapter];
  $('p-chapter').textContent = `${engine.chapter + 1}/${current.chapters.length} · ${ch.title}`;
  const reader = $('reader');
  reader.textContent = '';
  reader.lang = current.lang === 'und' ? '' : current.lang;
  reader.dir = 'auto';
  // add a heading unless the chapter text already opens with its title
  const norm = (x: string) => x.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
  const first = norm(engine.sentences[0] || '');
  const t = norm(ch.title).replace(/^\d+\s+/, '');
  if (!t || !(first.startsWith(t) || (first.length > 2 && t.endsWith(first)))) reader.append(el('h2', '', ch.title));
  // Rebuild paragraphs: walk the chapter text and wrap each sentence in a span.
  sentenceEls = [];
  sentenceOffsets = [];
  let acc = 0;
  const paras = ch.text.split(/\n{2,}/);
  let si = 0;
  const sentences = engine.sentences;
  for (const para of paras) {
    const p = el('p');
    p.dir = 'auto';
    const flat = para.replace(/\s*\n\s*/g, ' ');
    let pos = 0;
    while (si < sentences.length) {
      const s = sentences[si];
      const at = flat.indexOf(s.slice(0, Math.min(24, s.length)), pos);
      if (at === -1) break;
      if (at > pos) p.append(flat.slice(pos, at));
      const span = el('span', 's', s);
      const idx = si;
      span.addEventListener('click', () => {
        engine.jump(idx);
        if (!engine.playing) engine.play();
      });
      p.append(span, ' ');
      sentenceEls.push(span);
      sentenceOffsets.push(acc);
      acc += s.length + 1;
      pos = at + s.length;
      si++;
    }
    if (pos < flat.length && flat.slice(pos).trim()) p.append(flat.slice(pos));
    if (p.childNodes.length) reader.append(p);
  }
  // any sentences not matched to paragraph text (rare): append them so every index has an element
  if (si < sentences.length) {
    const p = el('p');
    p.dir = 'auto';
    for (; si < sentences.length; si++) {
      const span = el('span', 's', sentences[si]);
      const idx = si;
      span.addEventListener('click', () => engine.jump(idx));
      p.append(span, ' ');
      sentenceEls.push(span);
      sentenceOffsets.push(acc);
      acc += sentences[si].length + 1;
    }
    reader.append(p);
  }
  chapterOffset = current.chapters.slice(0, engine.chapter).reduce((n, c) => n + c.text.length + 1, 0);
  $<HTMLInputElement>('seek').max = String(Math.max(0, sentences.length - 1));
  reader.scrollTop = 0;
}

let lastOn: HTMLElement | null = null;
function highlight(i: number) {
  lastOn?.classList.remove('on');
  const s = sentenceEls[i];
  if (!s) return;
  s.classList.add('on');
  lastOn = s;
  const r = $('reader');
  const top = s.offsetTop - r.offsetTop;
  if (top < r.scrollTop + 40 || top > r.scrollTop + r.clientHeight * 0.6) {
    r.scrollTo({ top: Math.max(0, top - r.clientHeight * 0.3), behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
  }
}

function doneChars() {
  return chapterOffset + (sentenceOffsets[engine.index] || 0);
}

let seeking = false; // while the thumb is held, playback must not move it back
function chapterChars() {
  const n = sentenceOffsets.length;
  return n ? sentenceOffsets[n - 1] + (engine.sentences[n - 1]?.length || 0) : 0;
}
/** Bar and label for sentence `i` of this chapter (the current one, or the one under a held thumb). */
function paintProgress(i: number) {
  if (!current) return;
  const seek = $<HTMLInputElement>('seek');
  if (engine.finished && !seeking) {
    $('bar-fill').style.width = '100%';
    $('progress-label').textContent = 'Finished ✓';
    seek.value = seek.max;
    seek.setAttribute('aria-valuetext', 'Finished');
    return;
  }
  const total = chapterChars();
  const at = sentenceOffsets[i] || 0;
  const max = Number(seek.max) || 0;
  $('bar-fill').style.width = (max ? (i / max) * 100 : 0).toFixed(1) + '%'; // same scale as the thumb
  const chLeft = Math.max(1, Math.round((total - at) / 900 / engine.speed)); // ≈155 words a minute at 1×
  const bookDone = chapterOffset + at;
  const bookPct = current.totalChars ? Math.round((bookDone / current.totalChars) * 100) : 0;
  const bookLeft = Math.max(1, Math.round((current.totalChars - bookDone) / 900 / engine.speed));
  const label = $('progress-label');
  label.textContent = `${formatDuration(chLeft)} left in chapter`;
  label.title = `${bookPct}% of the book · ${formatDuration(bookLeft)} left in the book`;
  if (!seeking) seek.value = String(i);
  seek.setAttribute('aria-valuetext', `${formatDuration(chLeft)} left in this chapter, ${bookPct}% of the book`);
}
function updateProgressUi() {
  if (!seeking) paintProgress(engine.index);
}

function renderModel(m: ModelState) {
  const b = $('model-banner');
  if (m.s === 'loading') {
    // compressed responses report no real size: then use the known model size (≈165 MB)
    const total = m.total > m.loaded * 1.02 ? m.total : Math.max(MODEL_BYTES, m.loaded);
    const pct = Math.min(99, Math.round((m.loaded / total) * 100));
    b.innerHTML = '';
    const chip = el('div', 'chip-text', `Getting the natural voice ready… ${pct}%`);
    chip.title = engine.voice.kind === 'device' ? "Your device's own voice reads meanwhile. It switches by itself when it's ready." : '';
    b.append(chip);
    b.classList.add('chip');
    const bar = el('div', 'bar');
    const fill = el('div');
    fill.style.width = pct + '%';
    bar.append(fill);
    b.append(bar);
    b.hidden = !current;
  } else if (m.s === 'ready') {
    b.hidden = true;
    b.classList.remove('chip');
    if (!modelEverReady) {
      modelEverReady = true;
      void kvSet('modelReady', true);
    }
    if (pendingSampleVoice && current?.format === 'sample') {
      engine.queueVoice(pendingSampleVoice);
      updateVoiceLabel(pendingSampleVoice.id);
      toast(`Natural voice ready ✓ Switching to ${voiceName(pendingSampleVoice.id)}`);
    }
    pendingSampleVoice = null;
    if (pendingAutoSwitch && current?.lang === 'en' && engine.voice.kind === 'device') {
      pendingAutoSwitch = false;
      void decideSwitch();
    }
    refreshVoiceSheet();
  } else if (m.s === 'error') {
    b.classList.remove('chip');
    b.hidden = !current;
    b.textContent = "The natural voice couldn't start on this phone or computer. Your device's own voice keeps reading.";
    if (m.message) console.warn('natural voice:', m.message);
    pendingSampleVoice = null;
    if (current && samplePrerendered(current) && engine.voice.kind === 'natural') {
      // the sample keeps reading with its own Heart clips
      if (engine.voice.id !== SAMPLE_AUDIO.voice) engine.setVoice({ kind: 'natural', id: SAMPLE_AUDIO.voice }), updateVoiceLabel();
      return;
    }
    if (engine.voice.kind === 'natural' && current) {
      engine.setVoice({ kind: 'device', id: pickDeviceVoice(current.lang)?.voiceURI || '' });
      updateVoiceLabel();
    }
  }
}

/** Switch to the natural voice only if this device makes it faster than it is spoken. */
async function decideSwitch() {
  if (!current) return;
  const rtf = await engine.probe();
  if (!current || engine.voice.kind !== 'device') return;
  if (rtf !== null && rtf < 0.9) {
    engine.queueVoice({ kind: 'natural', id: engine.naturalId });
    updateVoiceLabel(engine.naturalId);
    toast('Natural voice ready ✓ Switching now');
  } else if (rtf !== null) offerPrepare(rtf);
}

function offerPrepare(rtf: number) {
  const b = $('model-banner');
  b.classList.remove('chip');
  b.textContent = '';
  console.info('natural voice speed vs real time:', rtf.toFixed(2));
  b.append(el('div', '', "The natural voice is ready, but this phone can't keep up with it live. Your device's own voice keeps reading. Get this chapter ready in the background and switch when it's done."));
  const btn = el('button', 'pill-btn', 'Get this chapter ready');
  btn.style.marginTop = '8px';
  btn.addEventListener('click', () => engine.prepare());
  b.append(btn);
  b.hidden = false;
}

let prepSwitched = '';
function renderPrepare(done: number, total: number) {
  if (!current) return;
  const b = $('model-banner');
  if (done >= total) {
    b.hidden = true;
    const k = `${current.id}|${engine.chapter}`;
    if (engine.voice.kind === 'device' && engine.preparing && prepSwitched !== k) {
      prepSwitched = k;
      engine.queueVoice({ kind: 'natural', id: engine.naturalId });
      updateVoiceLabel(engine.naturalId);
      toast('Chapter ready ✓ The natural voice starts at the next sentence');
    }
    return;
  }
  b.textContent = '';
  b.classList.remove('chip');
  const pct = Math.round((done / Math.max(1, total)) * 100);
  b.append(el('div', '', `Getting this chapter ready: ${pct}%. Keep EarShelf open.`));
  const bar = el('div', 'bar');
  const fill = el('div');
  fill.style.width = pct + '%';
  bar.append(fill);
  b.append(bar);
  b.hidden = false;
}

/* ---------- speed & voice ---------- */
function updateSpeedLabel() {
  $('speed').textContent = `${engine.speed}×`;
  $('speed').setAttribute('aria-label', `Playback speed ${engine.speed}×`);
}
function updateVoiceLabel(naturalId?: string) {
  const v = engine.voice;
  let label = 'Voice';
  if (naturalId || v.kind === 'natural') label = NATURAL_VOICES.find((n) => n.id === (naturalId || v.id))?.label.split(' ·')[0] || 'Natural';
  else label = (synth?.getVoices() || []).find((x) => x.voiceURI === v.id)?.name.replace(/^(Microsoft|Google)\s+/, '').split(/[ (-]/)[0] || 'Voice';
  $('voice-btn').textContent = label;
  $('voice-btn').setAttribute('aria-label', `Voice: ${label}`);
}

function refreshVoiceSheet() {
  const dlg = $<HTMLDialogElement>('voices');
  if (!dlg.open) return;
  buildVoiceSheet();
}

function buildVoiceSheet() {
  stopPreview(); // the old buttons are about to be replaced
  const body = $('voice-body');
  body.textContent = '';
  const english = current?.lang === 'en';
  const g1 = el('div', 'voice-group');
  g1.append(el('h4', '', 'Natural voices (English books)'));
  if (!english) g1.append(el('p', '', "Natural voices speak English only. This book looks like another language, so your device's own voice is the better fit."));
  else if (current && samplePrerendered(current)) g1.append(el('p', '', 'Heart reads this sample right away. The other voices download once (a minute or two on Wi-Fi), then work without internet. Tap ▶ to hear any of them now.'));
  else if (engine.model.s !== 'ready') g1.append(el('p', '', modelEverReady ? 'Getting ready…' : 'Downloads once (a minute or two on Wi-Fi), then works without internet.'));
  for (const v of NATURAL_VOICES) {
    const b = el('button', 'voice-opt');
    const cur = engine.voice.kind === 'natural' && engine.voice.id === v.id;
    if (cur) b.classList.add('cur');
    b.setAttribute('aria-pressed', String(cur));
    b.append(el('span', '', v.label.split(' ·')[0]), el('small', '', v.label.split(' · ').slice(1).join(' · ')));
    const row = el('div', 'voice-row');
    const hear = el('button', 'voice-hear');
    hear.type = 'button';
    hear.setAttribute('aria-label', `Hear ${v.label.split(' ·')[0]}`);
    setHear(hear, false);
    hear.hidden = !canOgg;
    hear.addEventListener('click', () => previewVoice(`./sample-audio/voice-${v.id}.ogg`, hear));
    row.append(b, hear);
    b.addEventListener('click', () => {
      pendingAutoSwitch = false;
      const nv: Voice = { kind: 'natural', id: v.id };
      void kvSet('voice', nv);
      if (current && samplePrerendered(current) && v.id !== SAMPLE_AUDIO.voice) {
        // only Heart is recorded for the sample: keep it reading until the chosen voice is on this device
        pendingSampleVoice = nv;
        if (engine.voice.kind !== 'natural') engine.setVoice({ kind: 'natural', id: SAMPLE_AUDIO.voice }), updateVoiceLabel();
        toast(`${voiceName(v.id)} is downloading (a minute or two on Wi-Fi). Heart keeps reading meanwhile.`);
        if (metered()) offerDownload();
        else engine.ensureModel();
        buildVoiceSheet();
        return;
      }
      if (current && samplePrerendered(current)) pendingSampleVoice = null; // back to Heart
      engine.setVoice(nv);
      updateVoiceLabel();
      buildVoiceSheet();
    });
    g1.append(row);
  }
  const g2 = el('div', 'voice-group');
  g2.append(el('h4', '', "Your device's voices (instant, every language)"));
  const sel = el('select', 'device-voices') as HTMLSelectElement;
  sel.setAttribute('aria-label', "Your device's voices");
  const all = synth?.getVoices() || [];
  const lang = current?.lang || 'en';
  const sorted = [...all].sort((a, b) => Number(b.lang.toLowerCase().startsWith(lang)) - Number(a.lang.toLowerCase().startsWith(lang)) || a.lang.localeCompare(b.lang));
  const ph = el('option', '', all.length ? 'Choose a voice…' : 'None on this phone or computer');
  ph.value = '';
  sel.append(ph);
  for (const v of sorted) {
    const o = el('option', '', `${v.name} (${v.lang})`) as HTMLOptionElement;
    o.value = v.voiceURI;
    if (engine.voice.kind === 'device' && engine.voice.id === v.voiceURI) o.selected = true;
    sel.append(o);
  }
  sel.addEventListener('change', () => {
    if (!sel.value) return;
    pendingAutoSwitch = false;
    const nv: Voice = { kind: 'device', id: sel.value };
    engine.setVoice(nv);
    void kvSet('voice', nv);
    updateVoiceLabel();
  });
  const devRow = el('div', 'voice-row');
  const devHear = el('button', 'voice-hear');
  devHear.type = 'button';
  devHear.setAttribute('aria-label', 'Hear the chosen device voice');
  setHear(devHear, false);
  devHear.disabled = !all.length;
  devHear.addEventListener('click', () => {
    const v = all.find((x) => x.voiceURI === sel.value) || all.find((x) => x.voiceURI === (engine.voice.kind === 'device' ? engine.voice.id : '')) || pickDeviceVoice(lang);
    if (!synth || !v) return;
    const again = previewBtn === devHear;
    stopPreview();
    if (again) return;
    if (engine.playing) engine.pause();
    const u = new SpeechSynthesisUtterance(SAMPLE_AUDIO.previewText);
    u.voice = v;
    u.lang = v.lang;
    u.onend = () => previewBtn === devHear && stopPreview();
    synth.cancel();
    previewBtn = devHear;
    devPreviewing = true;
    setHear(devHear, true);
    synth.speak(u);
  });
  devRow.append(sel, devHear);
  g2.append(devRow);
  body.append(english ? g1 : g2, english ? g2 : g1);
}

/* ---------- voice previews (pre-rendered, so they work before the download) ---------- */
const previewAudio = new Audio();
let previewBtn: HTMLElement | null = null;
let devPreviewing = false;
const STOP_SVG = '<svg class="ic sm" viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7h10v10H7z"/></svg>';
const HEAR_SVG = `<svg class="ic sm" viewBox="0 0 24 24" aria-hidden="true"><path d="${PLAY_PATH}"/></svg>`;
function setHear(btn: HTMLElement, on: boolean) {
  btn.classList.toggle('on', on);
  btn.setAttribute('aria-pressed', String(on));
  btn.innerHTML = on ? STOP_SVG : HEAR_SVG;
}
function stopPreview() {
  previewAudio.pause();
  if (devPreviewing) synth?.cancel(); // only our own preview: the engine is paused while one plays
  devPreviewing = false;
  if (previewBtn) setHear(previewBtn, false);
  previewBtn = null;
}
function previewVoice(src: string, btn: HTMLElement) {
  const again = previewBtn === btn;
  stopPreview();
  if (again) return; // second tap stops it
  if (engine.playing) engine.pause(); // never two voices at once
  previewBtn = btn;
  setHear(btn, true);
  previewAudio.src = src;
  void previewAudio.play().catch(() => stopPreview());
}
previewAudio.addEventListener('ended', stopPreview);
$('voices').addEventListener('close', stopPreview);

/* ---------- ui helpers ---------- */
let toastTimer: number | undefined;
let errUntil = 0; // an error message on screen is never covered by a tip
function toast(msg: string, err = false) {
  const t = $('toast');
  if (err) errUntil = Date.now() + 5000;
  t.textContent = msg;
  t.classList.toggle('err', err);
  t.classList.add('show');
  clearTimeout(toastTimer);
  toastTimer = window.setTimeout(() => t.classList.remove('show'), err ? 5000 : 2600);
}
function busy(text: string | null, progress?: number) {
  $('busy').hidden = text === null;
  if (text) $('busy-text').textContent = text;
  if (progress !== undefined) $('busy-fill').style.width = Math.round(Math.min(1, progress) * 100) + '%';
}

function backToLibrary() {
  engine.pause();
  setSleep(0);
  $('toast').classList.remove('show');
  current = null;
  $('player').hidden = true;
  $('library').hidden = false;
  $('model-banner').hidden = true;
  void renderLibrary();
}

/* ---------- full access / paywall (off unless paywallOn()) ---------- */
type PwReason = 'limit' | 'code';
function openPaywall(reason: PwReason) {
  if (!paywallOn() || isPro()) return;
  const d = $<HTMLDialogElement>('paywall');
  d.classList.toggle('code-mode', reason === 'code'); // a buyer coming back sees only the code box
  $('pw-paste').className = reason === 'code' ? 'primary-btn' : 'link-btn';
  $('pw-title').textContent = reason === 'code' ? 'Welcome back! Paste your code.' : 'Loved it? Keep listening';
  $('pw-lead').textContent = reason === 'code' ? 'Your code is in your Gumroad receipt email, in the box called "License key". Copy it, then tap Paste my code.' : limitLead();
  $('pw-later').textContent = reason === 'code' ? 'Close' : 'Not now';
  $('pw-msg').textContent = '';
  ($('pw-restore') as HTMLDetailsElement).open = reason === 'code';
  if (!d.open) d.showModal();
  if (reason === 'code') setTimeout(() => $('pw-key').focus(), 0);
}
/** Real numbers for the book in hand: how much is waiting. */
function limitLead(): string {
  const intro = `You've heard your ${FREE_MINUTES} free minutes.`;
  const none = `${intro} Get full access to keep listening to every book you add.`;
  if (!current || current.format === 'sample') return none;
  const heard = sentenceOffsets[engine.index] || 0; // part of the current chapter already heard
  const later = current.chapters.slice(engine.chapter + 1);
  const chars = chapterChars() - heard + later.reduce((n, c) => n + c.text.length, 0);
  if (chars <= 0) return none;
  const min = Math.max(1, Math.round(chars / 900 / engine.speed)); // ≈155 words a minute at 1×
  return `${intro} ${current.title} has about ${formatDuration(min)} to go, and your place is saved.`;
}
function renderProStatus() {
  const btn = $('pro-status');
  btn.hidden = !paywallOn();
  const l = savedLicense();
  btn.textContent = l ? `Full access ✓${l.email ? ` · ${l.email}` : ''}` : 'Already paid? Enter your code';
}
async function restorePro(key: string) {
  const msg = $('pw-msg');
  if (!key.trim()) {
    msg.textContent = 'Paste your access code first.';
    return;
  }
  msg.textContent = 'Checking your code…';
  const r = await verifyKey(key);
  if (r.ok) {
    storeLicense(r.license);
    msg.textContent = 'Full access ✓';
    renderProStatus();
    const resume = !!current && !engine.playing && !engine.finished;
    setTimeout(() => $<HTMLDialogElement>('paywall').close(), 700);
    toast(resume ? 'Full access ✓ Picking up where you left off' : 'Full access ✓ Listen as much as you like');
    if (current && engine.voice.kind === 'device' && current.lang === 'en') {
      if (engine.model.s === 'ready') {
        engine.queueVoice({ kind: 'natural', id: engine.naturalId });
        updateVoiceLabel(engine.naturalId);
      } else {
        pendingAutoSwitch = true; // switch (or offer Prepare) once the voice is ready
        engine.ensureModel();
      }
    }
    if (resume) engine.play();
    return;
  }
  msg.textContent =
    r.reason === 'network' ? 'No internet right now. Connect and tap Unlock again.' : r.reason === 'refunded' ? 'This code was refunded, so it no longer unlocks EarShelf.' : 'That code didn\'t work. Copy it again from your receipt email (the box called "License key") and paste it here.';
}
{
  for (const e of document.querySelectorAll('.pw-price')) e.textContent = PRO.price;
  $('pw-guarantee').textContent = String(PRO.guaranteeDays);
  ($('pw-buy') as HTMLAnchorElement).href = PRO.checkoutUrl;
  // Gumroad opens in a new tab: when they come back, the code box is already waiting
  $('pw-buy').addEventListener('click', () => {
    ($('pw-restore') as HTMLDetailsElement).open = true;
    $('pw-msg').textContent = 'After paying, check your email and paste the code from your receipt here.';
    setTimeout(() => ($('pw-key') as HTMLInputElement).focus(), 0);
  });
  const paste = $<HTMLButtonElement>('pw-paste');
  paste.hidden = !navigator.clipboard?.readText;
  paste.addEventListener('click', async () => {
    try {
      const t = (await navigator.clipboard.readText()).trim();
      if (!t) return void ($('pw-msg').textContent = 'Nothing copied yet. Copy the code from your email first.');
      ($('pw-key') as HTMLInputElement).value = t;
      void restorePro(t);
    } catch {
      $('pw-msg').textContent = 'Press and hold the box, then tap Paste.';
      $('pw-key').focus();
    }
  });
  $('pw-form').addEventListener('submit', (e) => {
    e.preventDefault();
    void restorePro(($('pw-key') as HTMLInputElement).value);
  });
  $('pw-later').addEventListener('click', () => $<HTMLDialogElement>('paywall').close());
  $('pro-status').addEventListener('click', () => {
    if (isPro()) return;
    openPaywall('code');
  });
  renderProStatus();
  if (paywallOn()) void recheck().then((r) => r === 'removed' && renderProStatus());
  // after the second copy of the count is back, so the gift is measured from the real number
  void trialRestored.then(() => grantBonus() && setTimeout(() => toast('A little gift: 2 more free minutes. The next page is on us'), 600));
  // the receipt email links to …/#unlock: the app opens with the code box ready
  window.addEventListener('hashchange', unlockFromLink); // the receipt link opened in a tab that was already open
  unlockFromLink();
}

/** The receipt email links to …/#unlock: open the code box (keeps any ?tags in the address). */
function unlockFromLink() {
  if (location.hash !== '#unlock') return;
  history.replaceState(history.state, '', location.pathname + location.search + (current ? '#book=' + current.id : ''));
  if (isPro()) toast('Full access is already on ✓');
  else openPaywall('code');
}

/* ---------- screen wake lock ---------- */
// Phones pause web pages when the screen locks; live voices stop with them. Keep the screen awake while
// playing (released on pause).
let wakeLock: any = null;
let wantAwake = false;
let requesting = false;
async function keepAwake(on: boolean) {
  wantAwake = on;
  try {
    if (on && !wakeLock && !requesting && 'wakeLock' in navigator && document.visibilityState === 'visible') {
      requesting = true;
      const lock = await (navigator as any).wakeLock.request('screen');
      requesting = false;
      if (!wantAwake) {
        await lock.release(); // paused while the request was in flight
        return;
      }
      wakeLock = lock;
      lock.addEventListener?.('release', () => {
        if (wakeLock === lock) wakeLock = null;
      });
    } else if (!on && wakeLock) {
      const lock = wakeLock;
      wakeLock = null;
      await lock.release();
    }
  } catch {
    requesting = false; // battery saver or unsupported: nothing to do
  }
}
function firstPlayTip() {
  if (!matchMedia('(pointer: coarse)').matches) return;
  try {
    if (localStorage.getItem('earshelf.tipLock')) return;
  } catch {
    return;
  }
  setTimeout(() => {
    // only in the player, and never over an error; if skipped, it waits for the next first play
    if ($('player').hidden || Date.now() < errUntil) return;
    try {
      if (localStorage.getItem('earshelf.tipLock')) return; // several plays inside 3 s: show it once
      localStorage.setItem('earshelf.tipLock', '1');
    } catch {
      /* storage blocked */
    }
    toast('Tip: the screen stays on while EarShelf reads. A chapter you got ready ahead can play with the screen off.');
  }, 3000);
}

/* ---------- sleep timer ---------- */
const SLEEP_STEPS = [0, 15, 30, 45, 60, -1]; // minutes; -1 = end of chapter
let sleepIdx = 0;
let sleepLeft = 0; // ms left on a timed sleep (0 = none); it only counts down while playing
let sleepFrom = 0; // when the current playing stretch started (0 = paused)
let sleepTick: number | undefined;
function sleepRemaining() {
  return sleepLeft - (sleepFrom ? Date.now() - sleepFrom : 0);
}
function sleepRun(playing: boolean) {
  if (!sleepLeft) return;
  if (playing && !sleepFrom) sleepFrom = Date.now();
  else if (!playing && sleepFrom) {
    sleepLeft = Math.max(1, sleepRemaining());
    sleepFrom = 0;
  }
}
function cycleSleep() {
  sleepIdx = (sleepIdx + 1) % SLEEP_STEPS.length;
  setSleep(SLEEP_STEPS[sleepIdx]);
  const m = SLEEP_STEPS[sleepIdx];
  toast(m === 0 ? 'Sleep timer off' : m === -1 ? 'Stops at the end of this chapter' : `Stops in ${m} minutes`);
}
function setSleep(min: number) {
  sleepIdx = Math.max(0, SLEEP_STEPS.indexOf(min));
  clearInterval(sleepTick);
  engine.stopAtChapterEnd = min === -1;
  sleepLeft = min > 0 ? min * 60_000 : 0;
  sleepFrom = sleepLeft && engine.playing ? Date.now() : 0;
  if (sleepLeft) sleepTick = window.setInterval(renderSleep, 15_000);
  renderSleep();
}
function renderSleep() {
  const btn = $('sleep');
  const m = SLEEP_STEPS[sleepIdx];
  let label = 'Sleep';
  if (m === -1) label = 'End of ch.';
  else if (sleepLeft) {
    const ms = sleepRemaining();
    if (ms <= 0) {
      if (engine.playing) {
        engine.pause();
        engine.prev(); // step back one sentence so the next play picks up the thread
      }
      return sleepEnded();
    }
    label = `${Math.ceil(ms / 60_000)} min`;
  }
  $('sleep-label').textContent = label;
  btn.classList.toggle('on', m !== 0);
  btn.setAttribute('aria-label', `Sleep timer: ${m === 0 ? 'off' : label}`);
}
function sleepEnded() {
  setSleep(0);
  toast('Sleep timer: paused. Good night');
}

/* ================= wiring ================= */
$('file').addEventListener('change', (e) => {
  const input = e.target as HTMLInputElement;
  if (input.files) void addFiles(input.files).finally(() => (input.value = ''));
});
const drop = $('drop');
['dragenter', 'dragover'].forEach((t) =>
  document.addEventListener(t, (e) => {
    e.preventDefault();
    drop.classList.add('over');
  }),
);
['dragleave', 'drop'].forEach((t) => document.addEventListener(t, () => drop.classList.remove('over')));
document.addEventListener('drop', (e) => {
  e.preventDefault();
  if (e.dataTransfer?.files.length) void addFiles(e.dataTransfer.files);
});
$('sample').addEventListener('click', () => void addSample());
$('back').addEventListener('click', () => history.back());
window.addEventListener('popstate', () => {
  if (location.hash === '#unlock') return; // the receipt link: handled by unlockFromLink, the player stays open
  const id = location.hash.match(/^#book=(.+)$/)?.[1];
  if (id && $('player').hidden) void openBook(decodeURIComponent(id));
  else if (!id && !$('player').hidden) backToLibrary();
});
{
  const seek = $<HTMLInputElement>('seek');
  seek.addEventListener('input', () => {
    seeking = true;
    paintProgress(Number(seek.value));
  });
  // Chrome sends pointerup BEFORE change, so the release itself commits the seek (resetting the thumb there
  // would cancel the change); a drag released where it started just repaints
  const commit = () => {
    if (!seeking) return;
    seeking = false;
    const v = Number(seek.value);
    if (v !== engine.index || engine.finished) engine.jump(v);
    else updateProgressUi();
  };
  for (const t of ['change', 'pointerup', 'pointercancel']) seek.addEventListener(t, commit);
  for (const t of ['keyup', 'blur']) {
    seek.addEventListener(t, () => {
      if (seeking) (seeking = false), updateProgressUi();
    });
  }
}
$('lib-error-close').addEventListener('click', () => showLibError([]));
$('lib-error-retry').addEventListener('click', () => $('file').click());
$('play').addEventListener('click', () => engine.toggle());
$('next').addEventListener('click', () => engine.skip(30));
$('prev').addEventListener('click', () => engine.skip(-15));
$('sleep').addEventListener('click', () => cycleSleep());
$('speed').addEventListener('click', () => {
  const i = SPEEDS.indexOf(engine.speed);
  const s = SPEEDS[(i + 1) % SPEEDS.length];
  engine.setSpeed(s);
  void kvSet('speed', s);
  updateSpeedLabel();
  updateProgressUi();
});
$('chapter-btn').addEventListener('click', () => {
  if (!current) return;
  const ol = $('chapter-list');
  ol.textContent = '';
  current.chapters.forEach((c, i) => {
    const li = el('li');
    const b = el('button');
    if (i === engine.chapter) b.classList.add('cur'), b.setAttribute('aria-current', 'true');
    else if (i < engine.chapter) b.classList.add('done');
    const min = Math.max(1, Math.round(c.text.length / 900 / engine.speed));
    b.dataset.meta = i === engine.chapter ? 'Now' : `${i < engine.chapter ? '✓ ' : ''}${formatDuration(min)}`;
    if (!/^\s*\d/.test(c.title)) b.append(el('span', 'num', String(i + 1)));
    b.append(el('span', '', c.title));
    b.addEventListener('click', () => {
      $<HTMLDialogElement>('chapters').close();
      engine.gotoChapter(i);
    });
    li.append(b);
    ol.append(li);
  });
  $<HTMLDialogElement>('chapters').showModal();
  ol.querySelector<HTMLElement>('.cur')?.scrollIntoView({ block: 'center' });
});
$('voice-btn').addEventListener('click', () => {
  buildVoiceSheet();
  $<HTMLDialogElement>('voices').showModal();
});
document.querySelectorAll('dialog').forEach((d) => {
  d.querySelector('.close')?.addEventListener('click', () => d.close());
  d.addEventListener('click', (e) => {
    if (e.target === d) d.close(); // tap on backdrop
  });
});
document.addEventListener('keydown', (e) => {
  const onSeek = (e.target as HTMLElement).id === 'seek';
  if ($('player').hidden || (!(onSeek && e.code === 'Space') && (e.target as HTMLElement).closest('input,select,textarea,dialog'))) return;
  if (e.code === 'Space' && (e.target as HTMLElement).closest('button')) return; // let the focused button handle it
  if (e.code === 'Space') {
    e.preventDefault();
    engine.toggle();
  } else if (e.key === 'ArrowRight') engine.next();
  else if (e.key === 'ArrowLeft') engine.prev();
});
synth?.addEventListener?.('voiceschanged', () => {
  if (current && engine.voice.kind === 'device' && !engine.voice.id) {
    const v = pickDeviceVoice(current.lang);
    if (v) engine.voice = { kind: 'device', id: v.voiceURI };
  }
  if (current) updateVoiceLabel();
  refreshVoiceSheet();
});
// save the position the moment the page is left (reload, tab close, app switch)
window.addEventListener('pagehide', saveNow);
document.addEventListener('visibilitychange', () => {
  if (document.hidden) saveNow();
  else {
    if (engine.playing) void keepAwake(true); // the browser drops the wake lock when the page is hidden
    if (sleepLeft) renderSleep();
  }
});

if ('serviceWorker' in navigator && import.meta.env.PROD) {
  void navigator.serviceWorker.register('./sw.js');
}
void renderLibrary();
// a reload inside the player reopens the same book (paused, at the saved position)
const startId = location.hash.match(/^#book=(.+)$/)?.[1];
if (startId) {
  history.replaceState({}, '', location.pathname);
  void getBook(decodeURIComponent(startId)).then((b) => b && openBook(b.id));
}

// test hook
(window as any).__earshelf = { engine, previewAudio, chimes: () => chimes };