aboutsummaryrefslogtreecommitdiff
path: root/internal/web/server_test.go
blob: 0754b08eb0292af9b26534ae03080d7e86b52ae7 (plain) (blame)
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
package web

import (
	"net"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/lukaszkasprzak/lectio/internal/bible"
	"github.com/lukaszkasprzak/lectio/internal/config"
	"github.com/lukaszkasprzak/lectio/internal/liturgy"
)

// TestServer exercises NewServer's handler tree end to end via httptest,
// against the same fixture HTML/hook internal/readings uses (see
// readings_test.go TestLoadModernRoutes): no real network, no real browser.
func TestServer(t *testing.T) {
	html, err := os.ReadFile("../liturgy/testdata/2026-07-22.html")
	if err != nil {
		t.Fatal(err)
	}
	fixtureServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write(html)
	}))
	defer fixtureServer.Close()
	liturgy.SetBaseURL(fixtureServer.URL + "/liturgia/%s/Ewangelia")
	cacheHome := t.TempDir()
	t.Setenv("XDG_CACHE_HOME", cacheHome)

	srv := NewServer(config.Default())

	t.Run("index page", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/?date=2026-07-22&v=wuj", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		body := rec.Body.String()
		// config.Default() -> UILanguage "en", so the gospel heading's part
		// label is localised to "Gospel" (render.LocalizeHeading); the
		// citation stays exactly as scraped.
		if !strings.Contains(body, "Gospel") {
			t.Errorf("body missing reading heading: %q", body)
		}
		if !strings.Contains(body, "htmx") {
			t.Errorf("body missing htmx reference")
		}
		if !strings.Contains(body, `id="theme"`) {
			t.Errorf("body missing theme <link>")
		}
		// Name is source-language (Polish), never translated, even
		// though the surrounding chrome is English -- see RenderReadings.
		if !strings.Contains(body, `class="dayinfo"`) || !strings.Contains(body, "Święto św. Marii Magdaleny") {
			t.Errorf("body missing day-info header: %q", body)
		}
	})

	t.Run("readings partial", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=2026-07-22&v=wuj&all=1", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		body := rec.Body.String()
		if strings.Contains(body, "<html") {
			t.Errorf("partial is not a fragment: %q", body)
		}
		// See "index page" above: config.Default() is English chrome.
		if !strings.Contains(body, "Gospel") {
			t.Errorf("partial missing reading heading: %q", body)
		}
	})

	t.Run("theme.css", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/theme.css?name=benedictines", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		if !strings.Contains(rec.Header().Get("Content-Type"), "css") {
			t.Errorf("Content-Type = %q, want it to contain css", rec.Header().Get("Content-Type"))
		}
	})

	t.Run("static", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/static/htmx.min.js", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		if rec.Body.Len() == 0 {
			t.Error("static/htmx.min.js served empty body")
		}
	})

	t.Run("theme.css unknown falls back", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/theme.css?name=does-not-exist", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200 (fallback to cfg.WebTheme/default)", rec.Code)
		}
		if rec.Body.Len() == 0 {
			t.Error("theme.css fallback served empty body")
		}
	})

	t.Run("readings partial interlinear", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=2026-07-22&v=wuj&v=vul&display=interlinear", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		body := rec.Body.String()
		if strings.Contains(body, "<html") {
			t.Errorf("partial is not a fragment: %q", body)
		}
		i := strings.Index(body, `class="vnum"`)
		if i == -1 {
			t.Fatalf("interlinear partial missing a vnum verse label: %q", body)
		}
		// Bound the first ilverse block by the next vnum span (each ilverse
		// carries exactly one), so the check covers every version's line
		// grouped under that one key, not just the first.
		block := body[i:]
		if j := strings.Index(body[i+1:], `class="vnum"`); j != -1 {
			block = body[i : i+1+j]
		}
		// config.Default() is English chrome: "Wujek (Polish)"/"Vulgate (Latin)".
		if !strings.Contains(block, "Wujek") || !strings.Contains(block, "Vulgate") {
			t.Errorf("interlinear verse block missing both version labels grouped together: %q", block)
		}
	})

	t.Run("readings partial vertical", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=2026-07-22&v=wuj&v=vul&display=vertical", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		if !strings.Contains(rec.Body.String(), "display-vertical") {
			t.Errorf("vertical partial missing display-vertical: %q", rec.Body.String())
		}
	})

	t.Run("readings partial interlinear substitutes bt", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=2026-07-22&v=bt&display=interlinear", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		body := rec.Body.String()
		if !strings.Contains(body, "Wujek") {
			t.Errorf("bt should be substituted with wuj in interlinear mode: %q", body)
		}
		if strings.Contains(body, "Biblia Tysiąclecia (niedziela.pl)") {
			t.Errorf("bt paragraph column should not appear in interlinear mode: %q", body)
		}
	})

	t.Run("readings partial bad display falls back to horizontal", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=2026-07-22&v=wuj&display=bogus", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		body := rec.Body.String()
		if strings.Contains(body, "display-vertical") || strings.Contains(body, "ilverse") {
			t.Errorf("bad display should fall back to horizontal, got: %q", body)
		}
	})

	t.Run("index page seeds display select from cfg", func(t *testing.T) {
		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/?date=2026-07-22&v=wuj", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		if !strings.Contains(rec.Body.String(), `name="display"`) {
			t.Errorf("body missing display select: %q", rec.Body.String())
		}
	})

	// Regression coverage for the ?date= path-traversal finding: resolveQuery
	// must reject anything that isn't YYYY-MM-DD and fall back to today(),
	// the same "normalize, don't trust" pattern requestDisplay already uses.
	t.Run("date path traversal does not read a planted cache file", func(t *testing.T) {
		// cacheDir() == filepath.Join(cacheHome, "lectio"), so
		// filepath.Join(cacheDir(), "../evil"+".json") resolves to
		// cacheHome/evil.json -- one level *above* the real cache dir, and
		// only reachable via an unvalidated "../" date. If the marker below
		// ever appears in a response, liturgy.Load read this planted file.
		evilPath := filepath.Join(cacheHome, "evil.json")
		evilJSON := `[{"Heading":"LEAKED-VIA-TRAVERSAL","PartID":"ewangelia","Paragraphs":[["s"]]}]`
		if err := os.WriteFile(evilPath, []byte(evilJSON), 0o644); err != nil {
			t.Fatal(err)
		}

		baseline := httptest.NewRecorder()
		srv.ServeHTTP(baseline, httptest.NewRequest("GET", "/readings?v=wuj", nil)) // no date -> today()
		if baseline.Code != http.StatusOK {
			t.Fatalf("baseline status = %d, want 200", baseline.Code)
		}

		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=../evil&v=wuj", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		body := rec.Body.String()
		if strings.Contains(body, "LEAKED-VIA-TRAVERSAL") {
			t.Fatalf("traversal date reached the planted cache file outside the cache dir: %q", body)
		}
		if body != baseline.Body.String() {
			t.Errorf("traversal date did not fall back to today() identically to omitting date\n got:  %q\nwant:  %q", body, baseline.Body.String())
		}
	})

	t.Run("date query with many ../ segments falls back to today, same as omitting date", func(t *testing.T) {
		baseline := httptest.NewRecorder()
		srv.ServeHTTP(baseline, httptest.NewRequest("GET", "/readings?v=wuj", nil)) // no date -> today()

		rec := httptest.NewRecorder()
		srv.ServeHTTP(rec, httptest.NewRequest("GET", "/readings?date=../../../../etc/hostname&v=wuj", nil))
		if rec.Code != http.StatusOK {
			t.Fatalf("status = %d, want 200", rec.Code)
		}
		if rec.Body.String() != baseline.Body.String() {
			t.Errorf("traversal-shaped date did not behave identically to omitting date\n got:  %q\nwant:  %q", rec.Body.String(), baseline.Body.String())
		}
	})
}

// TestBTHiddenForTraditional checks index.html's server-side initial-hidden
// state for the "bt" version checkbox: hidden (inline style) when the
// lectionary is traditional (bt is meaningless for missalemeum -- see
// render.EffectiveVersions), present and visible otherwise. This is
// presentation-only: it does not touch which versions actually load.
func TestBTHiddenForTraditional(t *testing.T) {
	srv := NewServer(config.Default())
	trad := httptest.NewRecorder()
	srv.ServeHTTP(trad, httptest.NewRequest("GET", "/?lectionary=traditional", nil))
	if !strings.Contains(trad.Body.String(), `id="ver-bt" style="display:none"`) {
		t.Errorf("bt checkbox not hidden for traditional")
	}
	modern := httptest.NewRecorder()
	srv.ServeHTTP(modern, httptest.NewRequest("GET", "/?lectionary=new", nil))
	b := modern.Body.String()
	if !strings.Contains(b, `id="ver-bt">`) || strings.Contains(b, `id="ver-bt" style="display:none"`) {
		t.Errorf("bt checkbox should be visible for modern")
	}
}

func TestReaderDefault(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/reader", nil))
	if rec.Code != 200 {
		t.Fatalf("status %d", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, `id="reader-root"`) || !strings.Contains(body, `id="pane"`) {
		t.Errorf("reader page missing root/pane")
	}
	if !strings.Contains(body, "Genesis") { // book <option> label (en dialect)
		t.Errorf("book options missing Genesis")
	}
}

func TestReaderPassage(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/reader?book=John&chap=3&v=wuj", nil))
	if rec.Code != 200 {
		t.Fatalf("status %d", rec.Code)
	}
	if b := rec.Body.String(); !strings.Contains(b, "John 3") || !strings.Contains(b, "3:16") {
		t.Errorf("passage missing heading/verse")
	}
}

func TestReaderCompareAndBTFilter(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	// bt must be dropped (no corpus); wuj+vul compared side by side.
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/reader?book=John&chap=3&v=bt&v=wuj&v=vul&display=vertical", nil))
	if rec.Code != 200 {
		t.Fatalf("status %d", rec.Code)
	}
	b := rec.Body.String()
	if !strings.Contains(b, "display-vertical") {
		t.Errorf("vertical compare layout missing")
	}
}

func TestReaderInvalidBook(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/reader?book=Nonsense", nil))
	if rec.Code != 200 { // defaults to the first book, never 500
		t.Errorf("invalid book status %d want 200", rec.Code)
	}
}

// TestRenderOrErrorNoSectionsLang checks the "no readings at all for this
// day" fragment (finding §1) follows lang instead of always being Polish.
func TestRenderOrErrorNoSectionsLang(t *testing.T) {
	html := string(renderOrError(nil, nil, "new", "horizontal", "en", liturgy.DayInfo{}, nil))
	if !strings.Contains(html, "no readings for this day") {
		t.Errorf("en renderOrError(no secs) = %q, want it to contain %q", html, "no readings for this day")
	}
	if strings.Contains(html, "czyta") {
		t.Errorf("en renderOrError(no secs) should not carry Polish wording: %q", html)
	}

	html = string(renderOrError(nil, nil, "new", "horizontal", "pl", liturgy.DayInfo{}, nil))
	if !strings.Contains(html, "brak czytań na ten dzień") {
		t.Errorf("pl renderOrError(no secs) = %q, want it to contain %q", html, "brak czytań na ten dzień")
	}
}

// TestIndexHTMLLangAttribute checks index.html's <html lang="..."> follows
// cfg.UILanguage (finding §6) instead of being hardcoded "pl".
func TestIndexHTMLLangAttribute(t *testing.T) {
	html, err := os.ReadFile("../liturgy/testdata/2026-07-22.html")
	if err != nil {
		t.Fatal(err)
	}
	fixtureServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write(html)
	}))
	defer fixtureServer.Close()
	liturgy.SetBaseURL(fixtureServer.URL + "/liturgia/%s/Ewangelia")
	t.Setenv("XDG_CACHE_HOME", t.TempDir())

	cfg := config.Default()
	cfg.UILanguage = "en"
	rec := httptest.NewRecorder()
	NewServer(cfg).ServeHTTP(rec, httptest.NewRequest("GET", "/?date=2026-07-22&v=wuj", nil))
	if !strings.Contains(rec.Body.String(), `<html lang="en">`) {
		t.Errorf(`en index page missing <html lang="en">: %q`, rec.Body.String()[:min(400, rec.Body.Len())])
	}

	cfg.UILanguage = "pl"
	rec = httptest.NewRecorder()
	NewServer(cfg).ServeHTTP(rec, httptest.NewRequest("GET", "/?date=2026-07-22&v=wuj", nil))
	if !strings.Contains(rec.Body.String(), `<html lang="pl">`) {
		t.Errorf(`pl index page missing <html lang="pl">: %q`, rec.Body.String()[:min(400, rec.Body.Len())])
	}
}

// TestChooseListener exercises chooseListener's port-selection logic
// directly (no HTTP serving): port==0 prefers defaultWebPort (1099) and
// falls back to a free OS port when 1099 is taken, and a non-zero port is
// bound exactly. Sandboxed/CI environments may not permit binding 1099 (or
// may race another process for it), so those assertions t.Skip rather than
// fail the suite.
func TestChooseListener(t *testing.T) {
	t.Run("zero port returns a listener with a non-zero port", func(t *testing.T) {
		ln, err := chooseListener(0)
		if err != nil {
			t.Fatalf("chooseListener(0) error: %v", err)
		}
		defer ln.Close()
		port := ln.Addr().(*net.TCPAddr).Port
		if port == 0 {
			t.Errorf("chooseListener(0) returned port 0, want non-zero")
		}
	})

	t.Run("falls back to a free port when 1099 is taken", func(t *testing.T) {
		pre, err := net.Listen("tcp", ":1099")
		if err != nil {
			t.Skipf("cannot bind :1099 in this environment, skipping fallback assertion: %v", err)
		}
		defer pre.Close()

		ln, err := chooseListener(0)
		if err != nil {
			t.Fatalf("chooseListener(0) error while 1099 is taken: %v", err)
		}
		defer ln.Close()
		port := ln.Addr().(*net.TCPAddr).Port
		if port == 1099 {
			t.Errorf("chooseListener(0) returned 1099 even though it was already taken")
		}
	})

	t.Run("explicit non-zero port is bound exactly", func(t *testing.T) {
		probe, err := net.Listen("tcp", ":0")
		if err != nil {
			t.Skipf("cannot bind :0 to pick a free port in this environment: %v", err)
		}
		want := probe.Addr().(*net.TCPAddr).Port
		probe.Close()

		ln, err := chooseListener(want)
		if err != nil {
			t.Skipf("could not bind explicit port %d (likely a race with another process): %v", want, err)
		}
		defer ln.Close()
		got := ln.Addr().(*net.TCPAddr).Port
		if got != want {
			t.Errorf("chooseListener(%d) bound port %d, want exactly %d", want, got, want)
		}
	})
}

// TestVsetEmptyShowsNothing guards the "uncheck all -> show nothing" behavior:
// a form submit (vset present) with no v param yields an empty pane, while a
// fresh visit (no vset) checks the config default and renders it.
func TestVsetEmptyShowsNothing(t *testing.T) {
	srv := NewServer(config.Default())

	// Form submit, every box unchecked: empty pane, nothing checked.
	empty := httptest.NewRecorder()
	srv.ServeHTTP(empty, httptest.NewRequest("GET", "/readings?vset=1&lectionary=traditional", nil))
	if b := strings.TrimSpace(empty.Body.String()); b != "" {
		t.Errorf("readings with vset and no v should be empty, got %q", b)
	}

	// Fresh visit (no vset): config default (bt for modern) box is checked.
	fresh := httptest.NewRecorder()
	srv.ServeHTTP(fresh, httptest.NewRequest("GET", "/", nil))
	if !strings.Contains(fresh.Body.String(), `value="bt" checked`) {
		t.Errorf("fresh visit should check the config default (bt) version box")
	}

	// Full page with vset and no v: no VERSION box checked (mono may be).
	idx := httptest.NewRecorder()
	srv.ServeHTTP(idx, httptest.NewRequest("GET", "/?vset=1", nil))
	for _, v := range bibleVersions {
		if strings.Contains(idx.Body.String(), `value="`+v+`" checked`) {
			t.Errorf("index with vset and no v: %q box should not be checked", v)
		}
	}
}

// TestTraditionalDropsPhantomBT guards the traditional case of "no version ->
// nothing": a phantom checked-but-hidden bt (carried over from modern) must not
// substitute to wuj on an explicit form submit, but a fresh visit keeps the
// bt->wuj default.
func TestTraditionalDropsPhantomBT(t *testing.T) {
	srv := NewServer(config.Default())

	// Explicit submit, only the phantom bt "checked": empty pane.
	phantom := httptest.NewRecorder()
	srv.ServeHTTP(phantom, httptest.NewRequest("GET", "/readings?vset=1&lectionary=traditional&v=bt", nil))
	if b := strings.TrimSpace(phantom.Body.String()); b != "" {
		t.Errorf("traditional vset+v=bt should be empty, got %d bytes", len(b))
	}

	// Explicit submit, bt phantom + a real corpus version: still renders it.
	withWuj := httptest.NewRecorder()
	srv.ServeHTTP(withWuj, httptest.NewRequest("GET", "/readings?vset=1&lectionary=traditional&v=bt&v=wuj", nil))
	if !strings.Contains(withWuj.Body.String(), "block") {
		t.Errorf("traditional vset+v=bt+v=wuj should still render wuj")
	}

	// Fresh visit (no vset): the bt->wuj default is kept and wuj is checked.
	fresh := httptest.NewRecorder()
	srv.ServeHTTP(fresh, httptest.NewRequest("GET", "/?lectionary=traditional", nil))
	if !strings.Contains(fresh.Body.String(), `value="wuj" checked`) {
		t.Errorf("fresh traditional visit should default to wuj (checked)")
	}
}

// TestReaderPaneOutsideForm guards the mono fix: #pane must render AFTER the
// controls </form> so its reading text inherits body's --font-reading (which
// the mono toggle flips) instead of the form's --font-ui.
func TestReaderPaneOutsideForm(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/reader", nil))
	b := rec.Body.String()
	f := strings.Index(b, "</form>")
	p := strings.Index(b, `id="pane"`)
	if f < 0 || p < 0 || p < f {
		t.Errorf("#pane must render after </form> (form@%d pane@%d)", f, p)
	}
}

// TestReaderArrowsDriveChapSelect guards the chapter-nav fix: the arrows drive
// the chap <select> (single source of truth) rather than a competing hx-vals
// "chap" param, and the server renders the requested book+chapter.
func TestReaderArrowsDriveChapSelect(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/reader?book=Luke&chap=12", nil))
	b := rec.Body.String()
	if !strings.Contains(b, "select[name=chap]") {
		t.Errorf("chapter arrows should drive the chap <select>")
	}
	if strings.Contains(b, `hx-vals='{"chap"`) {
		t.Errorf("chapter arrows must not use a competing hx-vals chap param")
	}
	if !strings.Contains(b, "Luke 12") {
		t.Errorf("server did not render the requested Luke 12")
	}
}

func TestSettingsGet(t *testing.T) {
	srv := NewServer(config.Default())
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, httptest.NewRequest("GET", "/settings", nil))
	if rec.Code != 200 {
		t.Fatalf("status %d", rec.Code)
	}
	b := rec.Body.String()
	if !strings.Contains(b, `name="ui_language"`) || !strings.Contains(b, `name="books"`) {
		t.Errorf("settings form missing fields")
	}
}

func TestSettingsPostAppliesLive(t *testing.T) {
	t.Setenv("LECTIO_CONFIG", filepath.Join(t.TempDir(), "config.toml"))
	srv := NewServer(config.Default()) // starts ui_language=en

	form := url.Values{}
	form.Set("lectionary", "new")
	form.Set("traditional_lang", "pl")
	form.Set("ui_language", "pl") // change it
	form.Set("sigla_style", "auto")
	form.Set("web_display", "vertical")
	form.Set("web_theme", "transfiguration")
	form.Set("default_version", "bt")
	form["versions"] = []string{"bt", "wuj", "vul", "grb", "drb"}
	form.Set("books", string(bibleDefaultBooks()))

	post := httptest.NewRequest("POST", "/settings", strings.NewReader(form.Encode()))
	post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, post)
	if rec.Code != http.StatusSeeOther {
		t.Fatalf("post status %d, want 303", rec.Code)
	}

	// Live-applied: the daily page now renders Polish chrome (ui_language=pl).
	idx := httptest.NewRecorder()
	srv.ServeHTTP(idx, httptest.NewRequest("GET", "/", nil))
	if !strings.Contains(idx.Body.String(), `lang="pl"`) {
		t.Errorf("ui_language change not applied live")
	}
}

func TestSettingsPostInvalidBooks(t *testing.T) {
	t.Setenv("LECTIO_CONFIG", filepath.Join(t.TempDir(), "config.toml"))
	srv := NewServer(config.Default())
	form := url.Values{}
	form.Set("lectionary", "new")
	form.Set("ui_language", "en")
	form.Set("web_display", "vertical")
	form.Set("web_theme", "transfiguration")
	form.Set("default_version", "bt")
	form["versions"] = []string{"bt"}
	form.Set("books", "this is not [valid toml")
	post := httptest.NewRequest("POST", "/settings", strings.NewReader(form.Encode()))
	post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, post)
	if rec.Code != 200 || !strings.Contains(rec.Body.String(), "books.toml") {
		t.Errorf("invalid books should re-render with an error, got %d", rec.Code)
	}
}

func bibleDefaultBooks() []byte { return bible.DefaultBooksTOML() }

// TestSettingsPostEmptyBooksPreservesFile guards that a submit without a books
// field never clobbers an existing books.toml override.
func TestSettingsPostEmptyBooksPreservesFile(t *testing.T) {
	dir := t.TempDir()
	t.Setenv("LECTIO_CONFIG", filepath.Join(dir, "config.toml"))
	booksPath := filepath.Join(dir, "books.toml")
	original := []byte("[en]\nJohn = [\"Jn\", \"John\"]\n")
	if err := os.WriteFile(booksPath, original, 0o644); err != nil {
		t.Fatal(err)
	}
	srv := NewServer(config.Default())
	form := url.Values{}
	form.Set("lectionary", "new")
	form.Set("ui_language", "en")
	form.Set("web_display", "vertical")
	form.Set("web_theme", "transfiguration")
	form.Set("default_version", "bt")
	form["versions"] = []string{"bt"} // no "books" field
	post := httptest.NewRequest("POST", "/settings", strings.NewReader(form.Encode()))
	post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, post)
	if rec.Code != http.StatusSeeOther {
		t.Fatalf("status %d", rec.Code)
	}
	if got, _ := os.ReadFile(booksPath); string(got) != string(original) {
		t.Errorf("empty books submit clobbered books.toml: got %q", got)
	}
}

func TestBookmarksFlow(t *testing.T) {
	t.Setenv("XDG_DATA_HOME", t.TempDir())
	srv := NewServer(config.Default())

	// Add via the reader form.
	form := url.Values{}
	form.Set("book", "John")
	form.Set("chap", "3")
	form.Set("verse", "16")
	form.Set("note", "for God so loved")
	form.Set("tags", "grace, gospel")
	post := httptest.NewRequest("POST", "/reader/bookmark", strings.NewReader(form.Encode()))
	post.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	rec := httptest.NewRecorder()
	srv.ServeHTTP(rec, post)
	if rec.Code != http.StatusSeeOther {
		t.Fatalf("add status %d", rec.Code)
	}

	// Listed on /bookmarks.
	list := httptest.NewRecorder()
	srv.ServeHTTP(list, httptest.NewRequest("GET", "/bookmarks", nil))
	b := list.Body.String()
	if !strings.Contains(b, "John") || !strings.Contains(b, "for God so loved") ||
		!strings.Contains(b, `book=John&chap=3`) || !strings.Contains(b, "John 3:16") {
		t.Errorf("bookmark not listed with verse:\n%s", b)
	}

	// Tag filter.
	byTag := httptest.NewRecorder()
	srv.ServeHTTP(byTag, httptest.NewRequest("GET", "/bookmarks?tag=grace", nil))
	if !strings.Contains(byTag.Body.String(), "John") {
		t.Errorf("tag filter dropped the bookmark")
	}
}