aboutsummaryrefslogtreecommitdiff
path: root/internal/web/server.go
blob: d7f0ebc73736a0124e9cce11b9ec5866b204f279 (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
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
// This file wires the package's render helpers (RenderReadings, Themes,
// themeCSS, the embedded static/templates FS) into an HTTP server: the full
// page (GET /), the HTMX reading-pane partial (GET /readings), a theme
// stylesheet endpoint (GET /theme.css) and the embedded static assets (GET
// /static/...).
package web

import (
	"fmt"
	"html/template"
	"io"
	"io/fs"
	"net"
	"net/http"
	"os"
	"os/exec"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

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

// bibleVersions is the fixed, Themes-independent list of scripture versions
// the web UI's checkboxes offer -- independent of any one cfg.Versions, so
// every visitor sees the same five choices regardless of their config file.
var bibleVersions = []string{"bt", "wuj", "vul", "grb", "drb"}

// server holds the live, mutable config + book table so /settings can apply
// changes to the running process. All handlers read a snapshot via get()/table().
type server struct {
	mu  sync.RWMutex
	cfg config.Config
	tbl *bible.BookTable
}

func (s *server) get() config.Config      { s.mu.RLock(); defer s.mu.RUnlock(); return s.cfg }
func (s *server) table() *bible.BookTable { s.mu.RLock(); defer s.mu.RUnlock(); return s.tbl }
func (s *server) apply(cfg config.Config, tbl *bible.BookTable) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.cfg = cfg
	if tbl != nil {
		s.tbl = tbl
	}
}

// NewServer builds lectio-web's route tree. cfg supplies the defaults
// (lectionary, versions, theme, offline) that requests can override via
// query parameters; it is never mutated -- /settings applies changes to a
// live, mutable copy held by server, which every handler reads per request.
func NewServer(cfg config.Config) http.Handler {
	tbl, _ := bible.LoadBookTable(config.UserBooksTOML())
	s := &server{cfg: cfg, tbl: tbl}

	mux := http.NewServeMux()
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { indexHandler(s.get())(w, r) })
	mux.HandleFunc("GET /readings", func(w http.ResponseWriter, r *http.Request) { readingsHandler(s.get())(w, r) })
	mux.HandleFunc("GET /reader", func(w http.ResponseWriter, r *http.Request) { readerHandler(s.get(), s.table())(w, r) })
	mux.HandleFunc("GET /theme.css", func(w http.ResponseWriter, r *http.Request) { themeCSSHandler(s.get())(w, r) })
	mux.HandleFunc("GET /settings", settingsGet(s))
	mux.HandleFunc("POST /settings", settingsPost(s))

	staticSub, err := fs.Sub(staticFS, "static")
	if err != nil {
		// Unreachable: "static" is embedded at build time by render.go.
		panic(err)
	}
	mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticSub))))

	return noStore(mux)
}

// noStore stops the browser caching any lectio-web response, so a rebuilt or
// reinstalled server never has an old page, base.css or theme.css served from
// cache (which presents as "switching themes stopped working" after an update).
func noStore(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store")
		h.ServeHTTP(w, r)
	})
}

// today is lectio-web's "no ?date=" default, in the YYYY-MM-DD form every
// other package's Date fields expect.
func today() string {
	return time.Now().Format("2006-01-02")
}

// dateRe validates a ?date= query param before it is ever handed to
// readings.Load/liturgy.Load, which build a filesystem cache path by string
// concatenation from it -- an unvalidated date is a path-traversal vector.
// Compiled once at package scope (not per request), the same shape as
// internal/cli's dateRe. See resolveQuery.
var dateRe = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)

// shiftDate adds days to date (YYYY-MM-DD); an unparsable date is returned
// unchanged, mirroring internal/tui's shiftDate.
func shiftDate(date string, days int) string {
	t, err := time.Parse("2006-01-02", date)
	if err != nil {
		return date
	}
	return t.AddDate(0, 0, days).Format("2006-01-02")
}

// requestVersions returns the versions requested via one or more repeated
// ?v= query params. The controls form always submits a hidden "vset" marker,
// so a request that carries "vset" but no "v" means the user unchecked EVERY
// version -- return none (the pane then shows nothing). A request with neither
// (a fresh visit or a bare link) falls back to cfg.WebVersions, else a single
// cfg.DefaultVersion, so a plain visit checks exactly one box.
func requestVersions(cfg config.Config, r *http.Request) []string {
	if vs, ok := r.URL.Query()["v"]; ok && len(vs) > 0 {
		return vs
	}
	if r.URL.Query().Has("vset") {
		return nil // form submitted with every box unchecked
	}
	if len(cfg.WebVersions) > 0 {
		return append([]string(nil), cfg.WebVersions...)
	}
	return []string{cfg.DefaultVersion}
}

// withoutVersion returns versions with every occurrence of drop removed.
func withoutVersion(versions []string, drop string) []string {
	kept := make([]string, 0, len(versions))
	for _, v := range versions {
		if v != drop {
			kept = append(kept, v)
		}
	}
	return kept
}

// queryBool reads a truthy/falsy query param ("1"/"true"/"on"/"yes" vs.
// "0"/"false"/"off"/"no"), falling back to def when the param is absent or
// unrecognized.
func queryBool(r *http.Request, name string, def bool) bool {
	if !r.URL.Query().Has(name) {
		return def
	}
	switch strings.ToLower(r.URL.Query().Get(name)) {
	case "1", "true", "on", "yes":
		return true
	case "0", "false", "off", "no":
		return false
	default:
		return def
	}
}

// requestLectionary returns the ?lectionary= override, falling back to
// cfg.Lectionary.
func requestLectionary(cfg config.Config, r *http.Request) string {
	if l := r.URL.Query().Get("lectionary"); l != "" {
		return l
	}
	return cfg.Lectionary
}

// requestDisplay returns the ?display= override (normalized the same way
// config.Load normalizes cfg.WebDisplay, so a bad/unknown value falls back
// to "horizontal" rather than reaching RenderReadings unchecked), falling
// back to cfg.WebDisplay when the param is absent.
func requestDisplay(cfg config.Config, r *http.Request) string {
	if d := r.URL.Query().Get("display"); d != "" {
		return config.NormalizeDisplay(d)
	}
	return cfg.WebDisplay
}

// resolveQuery resolves the date/lectionary/all/versions/display controls
// shared by indexHandler and readingsHandler from cfg (the defaults) and
// r's query params (the overrides) -- one place for both handlers so they
// can't drift.
func resolveQuery(cfg config.Config, r *http.Request) (date, lectionary string, all bool, versions []string, display string) {
	date = r.URL.Query().Get("date")
	if date == "" || !dateRe.MatchString(date) {
		date = today()
	}
	lectionary = requestLectionary(cfg, r)
	all = queryBool(r, "all", cfg.All)
	versions = requestVersions(cfg, r)
	// "bt" (the niedziela modern scrape) is invalid for the traditional
	// lectionary and is hidden in the form -- but a box hidden by CSS stays
	// checked, so switching modern->traditional carries a phantom v=bt that
	// EffectiveVersions would substitute to wuj, defeating "no version selected
	// -> nothing". On an explicit form submit (vset) drop that phantom bt; a
	// fresh visit (no vset) keeps bt so its bt->wuj default still shows.
	if lectionary == "traditional" && r.URL.Query().Has("vset") {
		versions = withoutVersion(versions, "bt")
	}
	display = requestDisplay(cfg, r)
	return date, lectionary, all, versions, display
}

// loadSections runs the readings router for one request: date/lectionary
// override cfg, all controls part filtering, and versions is swapped via
// render.OfflineVersions -- when cfg.Offline (any lectionary needs the
// network-free set), or when lectionary is "traditional" (pl is the
// niedziela.pl modern scrape, meaningless for missalemeum) -- before being
// handed back to the caller for rendering, so the caller's column labels
// always match what was actually loadable. dayInfo is the day's celebration
// identity (see liturgy.DayInfo), zero when the source carried none.
func loadSections(cfg config.Config, lectionary, date string, all bool, versions []string) (secs []liturgy.Section, dayInfo liturgy.DayInfo, effVersions []string, err error) {
	cfg.Lectionary = lectionary
	effVersions = render.EffectiveVersions(versions, lectionary, cfg.Offline)
	secs, dayInfo, err = readings.Load(cfg, readings.Options{
		Date:    date,
		Offline: cfg.Offline,
		All:     all,
	})
	return secs, dayInfo, effVersions, err
}

// indexData is what templates/index.html ranges/branches over.
type indexData struct {
	Date, PrevDate, NextDate string
	Lectionary               string
	VersionOpts              []versionOpt
	All                      bool
	ThemeOpts                []themeOpt
	Theme                    string
	Display                  string
	Mono                     bool
	Reading                  template.HTML
	// L holds the localised control labels (lectionary/layout/theme/...),
	// set from i18n.Get(cfg.UILanguage) -- index.html references its
	// fields (e.g. {{.L.Lectionary}}) instead of hardcoded Polish text.
	L i18n.UI
	// Lang is cfg.UILanguage, rendered into <html lang="...">.
	Lang string
}

type versionOpt struct {
	Code    string
	Checked bool
}

type themeOpt struct {
	Name     string
	Selected bool
}

// indexHandler serves the full page: controls reflecting the request's
// query (defaulting from cfg) plus the reading pane pre-rendered for that
// same query, so a plain (JS-less) GET / already shows today's gospel.
func indexHandler(cfg config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		date, lectionary, all, versions, display := resolveQuery(cfg, r)
		theme := r.URL.Query().Get("theme")
		if theme == "" {
			theme = cfg.WebTheme
		}

		// No version selected -> fetch nothing and show nothing (empty pane, no
		// day-info/headings); loadVersions stays nil so no box is checked.
		var reading template.HTML
		var loadVersions []string
		if len(versions) > 0 {
			secs, dayInfo, lv, err := loadSections(cfg, lectionary, date, all, versions)
			loadVersions = lv
			reading = renderOrError(secs, lv, lectionary, display, cfg.UILanguage, dayInfo, err)
		}

		// Check the boxes for the versions actually rendered (loadVersions),
		// not the raw request: traditional/offline substitute pl->wuj, so the
		// pl box must not show checked while Wujek is what's displayed.
		selected := map[string]bool{}
		for _, v := range loadVersions {
			selected[v] = true
		}
		versionOpts := make([]versionOpt, 0, len(bibleVersions))
		for _, v := range bibleVersions {
			versionOpts = append(versionOpts, versionOpt{Code: v, Checked: selected[v]})
		}

		themes := Themes()
		themeOpts := make([]themeOpt, 0, len(themes))
		for _, name := range themes {
			themeOpts = append(themeOpts, themeOpt{Name: name, Selected: name == theme})
		}

		data := indexData{
			Date:        date,
			PrevDate:    shiftDate(date, -1),
			NextDate:    shiftDate(date, 1),
			Lectionary:  lectionary,
			VersionOpts: versionOpts,
			All:         all,
			ThemeOpts:   themeOpts,
			Theme:       theme,
			Display:     display,
			Mono:        queryBool(r, "mono", cfg.WebMono),
			Reading:     reading,
			L:           i18n.Get(cfg.UILanguage),
			Lang:        cfg.UILanguage,
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tmpl.ExecuteTemplate(w, "index.html", data); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

// readingsHandler serves the HTMX reading-pane partial: a fragment only,
// produced entirely by RenderReadings (never re-implemented here).
func readingsHandler(cfg config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		date, lectionary, all, versions, display := resolveQuery(cfg, r)

		var reading template.HTML
		if len(versions) > 0 {
			secs, dayInfo, loadVersions, err := loadSections(cfg, lectionary, date, all, versions)
			reading = renderOrError(secs, loadVersions, lectionary, display, cfg.UILanguage, dayInfo, err)
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		io.WriteString(w, string(reading))
	}
}

// renderOrError returns RenderReadings' fragment, or (on a readings.Load
// error, or no sections at all for the date) a small escaped error
// paragraph, localised via lang -- readings.Load errors are expected in
// normal operation (an unpublished date, no network while online, ...) so
// the pane should show them, not 500.
func renderOrError(secs []liturgy.Section, versions []string, lectionary, display, lang string, dayInfo liturgy.DayInfo, err error) template.HTML {
	if err != nil {
		return template.HTML(`<p class="error">` + template.HTMLEscapeString(err.Error()) + `</p>`)
	}
	if len(secs) == 0 {
		return template.HTML(`<p class="error">` + template.HTMLEscapeString(i18n.Get(lang).NoReadingsDay) + `</p>`)
	}
	return RenderReadings(secs, versions, lectionary, display, lang, dayInfo)
}

// requestReaderVersions returns the corpus versions the reader request asks for
// (repeated ?v=), dropping "bt" (no corpus) and anything invalid; falling back
// to the configured default (or "wuj" when that is bt/invalid) so a plain visit
// shows exactly one column.
func requestReaderVersions(cfg config.Config, r *http.Request) []string {
	var out []string
	for _, v := range r.URL.Query()["v"] {
		if v != "bt" && config.ValidVersion(v) {
			out = append(out, v)
		}
	}
	if len(out) == 0 {
		d := cfg.DefaultVersion
		if d == "bt" || !config.ValidVersion(d) {
			d = "wuj"
		}
		out = []string{d}
	}
	return out
}

// findBook returns the BookInfo whose Canonical matches, and whether found.
func findBook(books []bible.BookInfo, canonical string) (bible.BookInfo, bool) {
	for _, b := range books {
		if b.Canonical == canonical {
			return b, true
		}
	}
	return bible.BookInfo{}, false
}

// clampChap keeps chap within the book's available chapters (contiguous in
// practice); 0 when the book has none in any corpus version.
func clampChap(chap int, chaps []int) int {
	if len(chaps) == 0 {
		return 0
	}
	if chap < chaps[0] {
		return chaps[0]
	}
	last := chaps[len(chaps)-1]
	if chap > last {
		return last
	}
	return chap
}

// atoiDefault parses s as an int, returning def when it is empty/unparsable.
func atoiDefault(s string, def int) int {
	if n, err := strconv.Atoi(strings.TrimSpace(s)); err == nil {
		return n
	}
	return def
}

type readerData struct {
	BookOpts           []bookOpt
	Chap               int
	PrevChap, NextChap int
	ChapOpts           []chapOpt
	VersionOpts        []versionOpt
	Display            string
	ThemeOpts          []themeOpt
	Theme              string
	Mono               bool
	Reading            template.HTML
	L                  i18n.UI
	Lang               string
}

type bookOpt struct {
	Value    string // canonical name (corpus/query value)
	Label    string // dialect display name
	Selected bool
}

type chapOpt struct {
	N        int
	Selected bool
}

// readerHandler serves GET /reader: a book picker (dialect names), chapter
// navigation and corpus-version compare, rendering the same reading-pane
// templates/themes as the daily view. The controls form re-fetches /reader and
// hx-selects #reader-root, so book/chapter/version selects stay in sync.
func readerHandler(cfg config.Config, tbl *bible.BookTable) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		books := tbl.Books(cfg.SiglaLang())
		if len(books) == 0 { // defensive: embedded table always has books
			http.Error(w, "web: no books", http.StatusInternalServerError)
			return
		}

		info, ok := findBook(books, r.URL.Query().Get("book"))
		if !ok {
			info = books[0]
		}
		versions := requestReaderVersions(cfg, r)
		chaps := UnionChapters(info.Canonical)
		first := 1
		if len(chaps) > 0 {
			first = chaps[0]
		}
		chap := clampChap(atoiDefault(r.URL.Query().Get("chap"), first), chaps)
		display := requestDisplay(cfg, r)
		theme := r.URL.Query().Get("theme")
		if theme == "" {
			theme = cfg.WebTheme
		}

		reading := RenderPassage(info.Canonical, info.Name, chap, versions, display, cfg.UILanguage)

		bookOpts := make([]bookOpt, 0, len(books))
		for _, b := range books {
			bookOpts = append(bookOpts, bookOpt{Value: b.Canonical, Label: b.Name, Selected: b.Canonical == info.Canonical})
		}
		chapOpts := make([]chapOpt, 0, len(chaps))
		for _, c := range chaps {
			chapOpts = append(chapOpts, chapOpt{N: c, Selected: c == chap})
		}
		selected := map[string]bool{}
		for _, v := range versions {
			selected[v] = true
		}
		versionOpts := make([]versionOpt, 0, len(readerCorpusVersions))
		for _, v := range readerCorpusVersions {
			versionOpts = append(versionOpts, versionOpt{Code: v, Checked: selected[v]})
		}
		themes := Themes()
		themeOpts := make([]themeOpt, 0, len(themes))
		for _, name := range themes {
			themeOpts = append(themeOpts, themeOpt{Name: name, Selected: name == theme})
		}

		prev, next := chap-1, chap+1
		if len(chaps) > 0 {
			prev = clampChap(chap-1, chaps)
			next = clampChap(chap+1, chaps)
		}

		data := readerData{
			BookOpts:    bookOpts,
			Chap:        chap,
			PrevChap:    prev,
			NextChap:    next,
			ChapOpts:    chapOpts,
			VersionOpts: versionOpts,
			Display:     display,
			ThemeOpts:   themeOpts,
			Theme:       theme,
			Mono:        queryBool(r, "mono", cfg.WebMono),
			Reading:     reading,
			L:           i18n.Get(cfg.UILanguage),
			Lang:        cfg.UILanguage,
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tmpl.ExecuteTemplate(w, "reader.html", data); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

// themeCSSHandler serves one theme's stylesheet: the requested name, or
// (unknown/invalid) cfg.WebTheme, or (that also unknown) the built-in
// default -- so an unrecognized ?name= degrades to a working theme instead
// of a broken page.
func themeCSSHandler(cfg config.Config) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		name := r.URL.Query().Get("name")
		css, err := themeCSS(name)
		if err != nil {
			css, err = themeCSS(cfg.WebTheme)
		}
		if err != nil {
			css, err = themeCSS(config.Default().WebTheme)
		}
		if err != nil {
			http.Error(w, "web: no theme available", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/css; charset=utf-8")
		w.Write(css)
	}
}

// settingsData drives templates/settings.html.
type settingsData struct {
	Cfg            config.Config
	Books          string       // current books.toml text (user override, else the embedded default)
	ThemeOpts      []themeOpt   // for the web_theme <select>
	VersionOpts    []versionOpt // all five, Checked if in Cfg.Versions
	WebVersionOpts []versionOpt // all five, Checked if in Cfg.WebVersions
	Saved          bool         // show a "saved" note (post-redirect)
	Error          string       // validation error to show (empty = none)
	L              i18n.UI
	Lang           string
}

func newSettingsData(cfg config.Config, books, errMsg string, saved bool) settingsData {
	themes := Themes()
	opts := make([]themeOpt, 0, len(themes))
	for _, name := range themes {
		opts = append(opts, themeOpt{Name: name, Selected: name == cfg.WebTheme})
	}

	versionsSet := map[string]bool{}
	for _, v := range cfg.Versions {
		versionsSet[v] = true
	}
	versionOpts := make([]versionOpt, 0, len(bibleVersions))
	for _, v := range bibleVersions {
		versionOpts = append(versionOpts, versionOpt{Code: v, Checked: versionsSet[v]})
	}

	webVersionsSet := map[string]bool{}
	for _, v := range cfg.WebVersions {
		webVersionsSet[v] = true
	}
	webVersionOpts := make([]versionOpt, 0, len(bibleVersions))
	for _, v := range bibleVersions {
		webVersionOpts = append(webVersionOpts, versionOpt{Code: v, Checked: webVersionsSet[v]})
	}

	return settingsData{
		Cfg:            cfg,
		Books:          books,
		ThemeOpts:      opts,
		VersionOpts:    versionOpts,
		WebVersionOpts: webVersionOpts,
		Saved:          saved,
		Error:          errMsg,
		L:              i18n.Get(cfg.UILanguage),
		Lang:           cfg.UILanguage,
	}
}

func currentBooksText() string {
	if b := config.UserBooksTOML(); len(b) > 0 {
		return string(b)
	}
	return string(bible.DefaultBooksTOML())
}

// settingsGet renders the settings form for the live config.
func settingsGet(s *server) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		data := newSettingsData(s.get(), currentBooksText(), "", r.URL.Query().Get("saved") == "1")
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tmpl.ExecuteTemplate(w, "settings.html", data); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}

// settingsPost validates and persists the submitted settings + books.toml, then
// applies them to the running server and redirects (PRG). On a validation error
// it re-renders the form with the message and the user's edits, HTTP 200.
func settingsPost(s *server) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := r.ParseForm(); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		cfg := s.get() // start from live cfg so Parts/SchemaVersion are preserved
		cfg.Lectionary = normLect(r.PostForm.Get("lectionary"), cfg.Lectionary)
		cfg.TraditionalLang = pickLang(r.PostForm.Get("traditional_lang"), cfg.TraditionalLang)
		cfg.UILanguage = config.NormalizeUILanguage(r.PostForm.Get("ui_language"))
		cfg.SiglaStyle = config.NormalizeSiglaStyle(r.PostForm.Get("sigla_style"))
		cfg.WebDisplay = config.NormalizeDisplay(r.PostForm.Get("web_display"))
		cfg.WebTheme = r.PostForm.Get("web_theme")
		cfg.DefaultVersion = r.PostForm.Get("default_version")
		cfg.Versions = r.PostForm["versions"]
		cfg.WebVersions = r.PostForm["web_versions"]
		cfg.All = r.PostForm.Get("all") != ""
		cfg.Offline = r.PostForm.Get("offline") != ""
		cfg.WebMono = r.PostForm.Get("web_mono") != ""
		cfg.Width = atoiOr(r.PostForm.Get("width"), cfg.Width)
		cfg.WebPort = atoiOr(r.PostForm.Get("web_port"), cfg.WebPort)
		cfg.Pager = r.PostForm.Get("pager")

		booksText := r.PostForm.Get("books")

		// Validate config.
		if err := config.Validate(cfg); err != nil {
			renderSettingsError(w, cfg, booksText, err.Error())
			return
		}
		// Validate books.toml (parse via the same loader the app uses).
		var newTbl *bible.BookTable
		if strings.TrimSpace(booksText) != "" {
			t, berr := bible.LoadBookTable([]byte(booksText))
			if berr != nil {
				renderSettingsError(w, cfg, booksText, "books.toml: "+berr.Error())
				return
			}
			newTbl = t
		}

		// Persist.
		if err := config.Save(cfg); err != nil {
			renderSettingsError(w, cfg, booksText, "saving config: "+err.Error())
			return
		}
		// Only write books.toml when the editor actually carried content, so a
		// submit with an empty/absent books field never clobbers an existing
		// override (the form always pre-fills the textarea).
		if strings.TrimSpace(booksText) != "" {
			if p, err := config.BooksPath(); err == nil {
				_ = os.WriteFile(p, []byte(booksText), 0o644)
			}
		}

		s.apply(cfg, newTbl)
		http.Redirect(w, r, "/settings?saved=1", http.StatusSeeOther)
	}
}

func renderSettingsError(w http.ResponseWriter, cfg config.Config, books, msg string) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	_ = tmpl.ExecuteTemplate(w, "settings.html", newSettingsData(cfg, books, msg, false))
}

// normLect normalizes a lectionary form value, falling back to def on anything invalid.
func normLect(v, def string) string {
	if n, ok := config.NormalizeLectionary(v); ok {
		return n
	}
	return def
}

// pickLang returns v if it is "pl"/"en", else def.
func pickLang(v, def string) string {
	if v == "pl" || v == "en" {
		return v
	}
	return def
}

func atoiOr(s string, def int) int {
	if n, err := strconv.Atoi(strings.TrimSpace(s)); err == nil {
		return n
	}
	return def
}

// defaultWebPort is the port chooseListener prefers when cfg.WebPort is 0.
const defaultWebPort = 1099

// chooseListener binds the port to serve on, on loopback only (127.0.0.1) --
// lectio-web is documented as a personal tool and Run prints an
// http://localhost/... URL, so it must not be reachable from the LAN. port==0
// means "prefer defaultWebPort (1099), else let the OS pick a free port"; a
// non-zero port is bound exactly (and its bind error surfaced if the port is
// in use).
func chooseListener(port int) (net.Listener, error) {
	if port != 0 {
		return net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
	}
	if ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", defaultWebPort)); err == nil {
		return ln, nil
	}
	return net.Listen("tcp", "127.0.0.1:0") // 1099 taken -> any free port
}

// Run starts lectio-web: listens on cfg.WebPort via chooseListener (0
// prefers 1099, falling back to a free OS port), prints the URL, best-effort
// opens it in a browser, and serves until the listener errors.
func Run(cfg config.Config) error {
	ln, err := chooseListener(cfg.WebPort)
	if err != nil {
		return err
	}
	port := ln.Addr().(*net.TCPAddr).Port
	url := fmt.Sprintf("http://localhost:%d", port)
	fmt.Println("lectio-web on " + url)

	openBrowser(url) // best-effort; ignore failure (no browser, headless, ...)

	return http.Serve(ln, NewServer(cfg))
}

// openBrowser best-effort launches the platform's "open a URL" command;
// any failure (missing command, no display, ...) is silently ignored, as
// lectio-web is fully usable by just visiting the printed URL manually.
func openBrowser(url string) {
	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "darwin":
		cmd = exec.Command("open", url)
	case "windows":
		cmd = exec.Command("cmd", "/c", "start", "", url)
	default:
		cmd = exec.Command("xdg-open", url)
	}
	_ = cmd.Start()
}