// Bible study section — parallel reader (#bible) and the home page's
// "verse of the day in every translation" panel.
//
// Ported from the standalone "Bible Parallel Reader" (Vite + TypeScript) into
// this site's no-build style: plain JSX, globals, loaded by index.html. It
// brings no chrome of its own — header, footer, stylesheet and the language
// toggle are the site's (components.jsx / styles.css / app.jsx `lang`).
// Tables and reference parsing live in bible-data.js (window.BIBLE).
// Conventions and rights rules: CLAUDE.md and docs/BIBLE_STUDY_MERGE.md.
//
// Verse text is rendered exactly as stored. Nothing here may transform it.

// ── Data access ────────────────────────────────────────────────────────
// One JSON file per book per translation: assets/bible/<folder>/<BookId>.json
//   { bookId, chapters: { "3": { "16": "…" } }, rangeEnds?: { "105": { "5": 6 } } }
// rangeEnds marks verses the source edition prints as one block (5–6): the
// text sits under the first number and the entry gives the last.
const BibleStore = (() => {
  const B = window.BIBLE;
  const books = new Map();    // "folder:BookId" → Promise<book file>
  const resolved = new Map(); // "folder:BookId" → book file, once loaded
  // Translations read live from API.Bible through /api/apibible (the NIV).
  const apiChapters = new Map(); // "tid|BookId|c" → Promise<chapter result>
  const apiResolved = new Map(); // same key → chapter result, once loaded
  const apiCopyright = new Map(); // tid → copyright text from API.Bible
  let apiStatusPromise = null;

  // Which API translations the server can serve: { niv: true|false }.
  // Anything but a clear yes (no key on the server, a local preview with no
  // server at all) counts as "not available", and the reader falls back to
  // the local editions.
  function apiStatus() {
    if (!apiStatusPromise) {
      apiStatusPromise = fetch("/api/apibible?status=1")
        .then((r) => (r.ok ? r.json() : {}))
        .then((s) => (s && typeof s === "object" ? s : {}))
        .catch(() => ({}));
    }
    return apiStatusPromise;
  }

  function getApiChapter(tid, bookId, chapter) {
    const key = tid + "|" + bookId + "|" + chapter;
    if (!apiChapters.has(key)) {
      const p = fetch("/api/apibible?v=" + encodeURIComponent(tid) + "&b=" + encodeURIComponent(bookId) + "&c=" + chapter)
        .then(async (r) => {
          const data = await r.json().catch(() => ({}));
          if (!r.ok || !data.ok) {
            const status = r.status === 503 ? "unavailable" : "error";
            return { id: tid, bookId, chapter, status, verses: {}, rangeEnds: {}, message: data.error || ("HTTP " + r.status) };
          }
          const verses = {};
          for (const [k, v] of Object.entries(data.verses || {})) if (Number(k) > 0) verses[Number(k)] = v;
          const rangeEnds = {};
          for (const [k, v] of Object.entries(data.rangeEnds || {})) rangeEnds[Number(k)] = v;
          if (data.copyright) apiCopyright.set(tid, data.copyright);
          const res = { id: tid, bookId, chapter, status: "ok", verses, rangeEnds, fumsToken: data.fumsToken || null };
          apiResolved.set(key, res);
          return res;
        })
        .catch(() => ({ id: tid, bookId, chapter, status: "error", verses: {}, rangeEnds: {} }));
      // Only a good answer is kept; a failure is asked again next time.
      p.then((res) => { if (res.status !== "ok" && apiChapters.get(key) === p) apiChapters.delete(key); });
      apiChapters.set(key, p);
    }
    return apiChapters.get(key);
  }

  function loadBook(tid, bookId) {
    const t = B.TRANSLATION_BY_ID[tid];
    if (!t || !B.BOOK_BY_ID[bookId]) return Promise.reject(new Error("unknown translation or book"));
    const key = t.folder + ":" + bookId;
    if (!books.has(key)) {
      const p = fetch("assets/bible/" + t.folder + "/" + bookId + ".json")
        .then((r) => { if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); })
        .then((data) => { resolved.set(key, data); return data; });
      // A failed load must not be cached, or one dropped request would leave
      // that book unreadable until the page is reloaded.
      p.catch(() => { if (books.get(key) === p) books.delete(key); });
      books.set(key, p);
    }
    return books.get(key);
  }

  async function getChapter(tid, bookId, chapter) {
    const tr = B.TRANSLATION_BY_ID[tid];
    if (tr && tr.api) return getApiChapter(tid, bookId, chapter);
    try {
      const book = await loadBook(tid, bookId);
      const verses = {};
      for (const [k, v] of Object.entries(book.chapters[String(chapter)] || {})) {
        const n = Number(k);
        if (n > 0) verses[n] = v;
      }
      const rangeEnds = {};
      for (const [k, v] of Object.entries((book.rangeEnds || {})[String(chapter)] || {})) rangeEnds[Number(k)] = v;
      return { id: tid, bookId, chapter, status: "ok", verses, rangeEnds };
    } catch (e) {
      return { id: tid, bookId, chapter, status: "error", verses: {}, rangeEnds: {} };
    }
  }

  // The verses a passage covers, in order: [{ c, n, end, text }]. A grouped
  // block is included whenever any part of it falls inside the passage.
  // null = this translation has nothing there (or could not be loaded).
  async function getPassage(tid, p) {
    const out = [];
    for (let c = p.chapter; c <= (p.endChapter || p.chapter); c++) {
      const ch = await getChapter(tid, p.bookId, c);
      if (ch.status !== "ok") return null;
      for (const n of Object.keys(ch.verses).map(Number).sort((a, b) => a - b)) {
        if (B.inPassage({ ...p, endChapter: p.endChapter || p.chapter }, c, n, ch.rangeEnds[n])) {
          out.push({ c, n, end: ch.rangeEnds[n] || null, text: ch.verses[n] });
        }
      }
    }
    return out.length ? out : null;
  }

  // Highest verse number in a chapter across the given translations, from
  // books already loaded (0 if none is). Used to fill the verse pickers.
  function verseCount(tids, bookId, c) {
    let max = 0;
    for (const tid of tids) {
      const t = B.TRANSLATION_BY_ID[tid];
      if (t && t.api) {
        const res = apiResolved.get(tid + "|" + bookId + "|" + c);
        if (res) for (const k of Object.keys(res.verses)) max = Math.max(max, Number(k));
        continue;
      }
      const book = t && resolved.get(t.folder + ":" + bookId);
      if (!book) continue;
      const ch = book.chapters[String(c)] || {};
      for (const k of Object.keys(ch)) max = Math.max(max, Number(k));
      for (const v of Object.values((book.rangeEnds || {})[String(c)] || {})) max = Math.max(max, v);
    }
    return max;
  }

  // Keyword search across whole translations. Books are fetched a few at a
  // time and scanned in canonical order, stopping once `limit` is reached.
  async function search(query, tids, limit) {
    tids = tids.filter((tid) => B.TRANSLATION_BY_ID[tid] && !B.TRANSLATION_BY_ID[tid].api);
    const q = String(query).trim().toLowerCase();
    const hits = [];
    if (q.length < 2) return hits;
    const BATCH = 6;
    for (const tid of tids) {
      for (let i = 0; i < B.BOOKS.length; i += BATCH) {
        const batch = B.BOOKS.slice(i, i + BATCH);
        const files = await Promise.all(batch.map((b) => loadBook(tid, b.id).catch(() => null)));
        for (let k = 0; k < batch.length; k++) {
          const file = files[k];
          if (!file) continue;
          for (const [chStr, verses] of Object.entries(file.chapters)) {
            for (const [vStr, text] of Object.entries(verses)) {
              if (text.toLowerCase().includes(q)) {
                hits.push({ tid, bookId: batch[k].id, chapter: Number(chStr), verse: Number(vStr), text });
                if (hits.length >= limit) return hits;
              }
            }
          }
        }
      }
    }
    return hits;
  }

  // FUMS tokens of the API chapters a passage covers, once they are loaded.
  function apiTokens(tid, p) {
    const out = [];
    for (let c = p.chapter; c <= (p.endChapter || p.chapter); c++) {
      const r = apiResolved.get(tid + "|" + p.bookId + "|" + c);
      if (r && r.fumsToken) out.push(r.fumsToken);
    }
    return out;
  }

  return { loadBook, getChapter, getPassage, verseCount, search, apiStatus, apiTokens, copyright: (tid) => apiCopyright.get(tid) || null };
})();
window.BibleStore = BibleStore;

// ── API.Bible usage reporting (FUMS) ───────────────────────────────────
// API.Bible's licence requires its Fair Use Management System to be told
// each time its Scripture is shown. Its script is loaded only when an API
// translation is on screen, never on other pages.
const BIBLE_FUMS_SRC = "https://pkg.api.bible/fumsV3.min.js";
const bibleFumsSent = new Set();
function bibleTrackFums(tokens) {
  const fresh = (tokens || []).filter((tk) => tk && !bibleFumsSent.has(tk));
  if (!fresh.length) return;
  fresh.forEach((tk) => bibleFumsSent.add(tk));
  window.fumsData = window.fumsData || [];
  window.fums = window.fums || function () { window.fumsData.push(arguments); };
  if (!document.querySelector('script[src="' + BIBLE_FUMS_SRC + '"]')) {
    const s = document.createElement("script");
    s.src = BIBLE_FUMS_SRC;
    s.async = true;
    document.head.appendChild(s);
  }
  window.fums("trackView", fresh);
}

// "Study this verse" links (home panel, a day's page) open the chosen verses
// themselves, not the whole chapter, whatever view was used last time.
const BIBLE_OPEN_SELECTED_KEY = "adm:bible:open-selected";
function bibleMarkStudyLink() {
  try { sessionStorage.setItem(BIBLE_OPEN_SELECTED_KEY, "1"); } catch (e) { /* storage unavailable */ }
}
window.bibleMarkStudyLink = bibleMarkStudyLink;

// ── Small helpers ──────────────────────────────────────────────────────
// Script of a translation's text, for the lang attribute (fonts, hyphenation).
function bibleTextLang(tid) {
  if (tid === "cuvmps" || tid === "csbs") return "zh-Hans";
  if (tid === "cuvmpt" || tid === "csbt") return "zh-Hant";
  return "en";
}
function bibleBookName(bookId, lang) {
  const b = window.BIBLE.BOOK_BY_ID[bookId];
  return b ? (lang === "cht" ? b.nameZh : b.nameEn) : bookId;
}
// 約翰福音 3 · 3–4 · 3:16 · 3:16–18 · 3:16–章末 · 3:16–4:3 · 3:16–4章末
function biblePassageLabel(p, lang) {
  const cht = lang === "cht";
  let s = bibleBookName(p.bookId, lang) + " " + p.chapter;
  const end = p.endChapter || p.chapter;
  if (p.verseFrom == null) return end > p.chapter ? s + "–" + end : s;
  s += ":" + p.verseFrom;
  if (end > p.chapter) return s + "–" + end + (p.verseTo == null ? (cht ? "章末" : ":end") : ":" + p.verseTo);
  if (p.verseTo == null) return s + "–" + (cht ? "章末" : "end");
  return p.verseTo !== p.verseFrom ? s + "–" + p.verseTo : s;
}
function bibleTranslationName(tid, lang) {
  const t = window.BIBLE.TRANSLATION_BY_ID[tid];
  return t ? (lang === "cht" ? t.cht : t.eng) : tid;
}

// Reader settings kept in this browser. v1 held a single reference; it is
// carried over as the first passage.
const BIBLE_PREFS_KEY = "adm:bible:prefs:v2";
function bibleLoadPrefs() {
  const B = window.BIBLE;
  // columnsChosen: the reader picked translations themselves. Until then the
  // columns follow the interface language (B.DEFAULT_COLUMNS_BY_LANG).
  const fallback = { columns: B.DEFAULT_COLUMNS.slice(), columnsChosen: false, passages: [{ ...B.DEFAULT_REF }], view: "selected", wide: true };
  const read = (key) => { try { return JSON.parse(localStorage.getItem(key) || "null"); } catch (e) { return null; } };
  const p = read(BIBLE_PREFS_KEY) || read("adm:bible:prefs:v1");
  if (!p || typeof p !== "object") return fallback;
  const seen = new Set();
  const columns = (Array.isArray(p.columns) ? p.columns : [])
    .filter((id) => B.TRANSLATION_BY_ID[id] && !seen.has(id) && seen.add(id))
    .slice(0, B.MAX_COLUMNS);
  const raw = Array.isArray(p.passages) ? p.passages : [p];
  const passages = raw.map((x) => B.normalizePassage(x)).filter(Boolean).map((r) => r.passage).slice(0, B.MAX_PASSAGES);
  return {
    columns: columns.length ? columns : fallback.columns,
    columnsChosen: p.columnsChosen === true && columns.length > 0,
    passages: passages.length ? passages : fallback.passages,
    view: p.view === "chapter" ? "chapter" : "selected", // "paged" (2 per page) was retired 2026-11-18
    wide: p.wide !== false,
  };
}
function bibleSavePrefs(prefs) {
  try { localStorage.setItem(BIBLE_PREFS_KEY, JSON.stringify(prefs)); } catch (e) { /* storage unavailable */ }
}

// ── Copyright notices ──────────────────────────────────────────────────
// Shown directly beneath whatever passage is on screen. For the four GBI
// editions this is a condition of use: GBI's own wording, in full, English
// and Chinese together, whichever interface language is active.
function BibleRights({ ids, lang, numbered }) {
  const B = window.BIBLE;
  const shown = ids.filter((id) => B.RIGHTS[id] || B.PD_RIGHTS[id] || B.API_RIGHTS[id]);
  if (!shown.length) return null;
  return (
    <div className={"bible-rights" + (numbered ? " is-aligned" : "")} style={numbered ? { "--cols": ids.length } : undefined}>
      {shown.map((id) => {
        const cls = "bible-rights-item" + (numbered ? " bible-col-" + (ids.indexOf(id) + 1) : "");
        if (B.RIGHTS[id]) {
          return (
            <p className={cls} key={id}>
              <span lang="en">{B.RIGHTS[id].eng}</span>{"\n"}
              <span lang={bibleTextLang(id)}>{B.RIGHTS[id].zh}</span>
            </p>
          );
        }
        // Public-domain edition: its status and source, both languages.
        if (B.PD_RIGHTS[id]) {
          return (
            <p className={cls} key={id}>
              <span lang="en">{B.PD_RIGHTS[id].eng}</span>{"\n"}
              <span lang="zh-Hant">{B.PD_RIGHTS[id].zh}</span>
            </p>
          );
        }
        // API.Bible translation: the publisher's copyright text as API.Bible
        // supplies it, with the holder and API.Bible named.
        const r = B.API_RIGHTS[id];
        return (
          <p className={cls + " bible-rights-api"} key={id} lang="en">
            {BibleStore.copyright(id) || r.notice}{"\n"}
            {r.holder ? <><a href={r.holderUrl} target="_blank" rel="noopener">{r.holder}</a>{" · "}</> : null}
            <a href="https://api.bible" target="_blank" rel="noopener">API.Bible</a>
            {window.location.hash === "#bible/about" ? null : <>{" · "}<a href="#bible/about">{lang === "cht" ? "完整版權資訊" : "Full copyright details"}</a></>}
          </p>
        );
      })}
    </div>
  );
}

// ── Translation columns ────────────────────────────────────────────────
function BiblePicker({ columns, available, onChange, lang }) {
  const B = window.BIBLE;
  const t = (c, e) => (lang === "cht" ? c : e);

  function setCount(n) {
    if (n === columns.length) return;
    if (n < columns.length) { onChange(columns.slice(0, n)); return; }
    const next = columns.slice();
    for (const tr of B.TRANSLATIONS) {
      if (next.length >= n) break;
      if (available && !available.includes(tr.id)) continue;
      if (!next.includes(tr.id)) next.push(tr.id);
    }
    onChange(next);
  }
  function setAt(i, id) {
    if (columns.includes(id) && columns[i] !== id) return;
    const next = columns.slice();
    next[i] = id;
    onChange(next);
  }

  return (
    <div className="bible-picker">
      <div className="bible-count" role="group" aria-label={t("對照譯本數目", "Number of translations")}>
        <span className="bible-field-label">{t("對照", "Compare")}</span>
        {[1, 2, 3, 4].map((n) => (
          <button key={n} type="button" className={"bible-seg" + (columns.length === n ? " active" : "")}
            aria-pressed={columns.length === n} onClick={() => setCount(n)}>
            {n}
          </button>
        ))}
        <span className="bible-field-unit">{t("個譯本", columns.length === 1 ? "translation" : "translations")}</span>
      </div>
      <div className="bible-chips">
        {columns.map((id, i) => (
          <label className={"bible-chip bible-col-" + (i + 1)} key={i}>
            <span className="bible-chip-num" aria-hidden="true">{i + 1}</span>
            <select value={id} lang={lang === "cht" ? bibleTextLang(id) : "en"} onChange={(e) => setAt(i, e.target.value)}
              aria-label={t("第 " + (i + 1) + " 欄譯本", "Translation for column " + (i + 1))}>
              {B.TRANSLATIONS.filter((tr) => !available || available.includes(tr.id) || tr.id === id).map((tr) => {
                const taken = columns.includes(tr.id) && tr.id !== id;
                return (
                  <option key={tr.id} value={tr.id} disabled={taken}>
                    {(lang === "cht" ? tr.cht : tr.eng) + (taken ? t("（已選）", " (selected)") : "")}
                  </option>
                );
              })}
            </select>
          </label>
        ))}
      </div>
    </div>
  );
}

// ── Book / chapter / verse, one row per passage ────────────────────────
// A passage covers one chapter or two in a row; the "To" list therefore
// offers the rest of this chapter and all of the next one.
function BiblePassageEditor({ passage, index, count, verseCount, onChange, onRemove, lang }) {
  const B = window.BIBLE;
  const t = (c, e) => (lang === "cht" ? c : e);
  const p = passage;
  const book = B.BOOK_BY_ID[p.bookId];
  const ch = p.chapter;
  const next = ch < book.chapters ? ch + 1 : null;
  const span = (n, extra) => Array.from({ length: Math.max(n, extra || 0) }, (_, i) => i + 1);
  const go = (patch) => {
    const r = B.normalizePassage({ ...p, ...patch });
    if (r) onChange(r.passage);
  };
  const toValue = p.endChapter + ":" + (p.verseTo == null ? "end" : p.verseTo);
  const fromList = span(verseCount(ch), p.verseFrom);
  const group = (testament) => B.BOOKS.filter((b) => b.testament === testament).map((b) => (
    <option key={b.id} value={b.id}>{lang === "cht" ? b.nameZh + " " + b.nameEn : b.nameEn}</option>
  ));

  let toOptions;
  if (p.verseFrom == null) {
    toOptions = [<option key="a" value={ch + ":end"}>{t("整章", "Whole chapter")}</option>];
    if (next) toOptions.push(<option key="b" value={next + ":end"}>{t("連第 " + next + " 章（共兩章）", "Through chapter " + next)}</option>);
  } else {
    const here = span(verseCount(ch), p.endChapter === ch ? p.verseTo : 0).filter((v) => v >= p.verseFrom);
    toOptions = [
      <optgroup key="g1" label={t("第 " + ch + " 章", "Chapter " + ch)}>
        {here.map((v) => <option key={v} value={ch + ":" + v}>{v === p.verseFrom ? v + t("（只此一節）", " (this verse only)") : v}</option>)}
        <option value={ch + ":end"}>{t("至本章末", "End of chapter")}</option>
      </optgroup>,
    ];
    if (next) {
      const there = span(verseCount(next), p.endChapter === next ? p.verseTo : 0);
      toOptions.push(
        <optgroup key="g2" label={t("跨至第 " + next + " 章", "Into chapter " + next)}>
          {there.map((v) => <option key={v} value={next + ":" + v}>{next + ":" + v}</option>)}
          <option value={next + ":end"}>{t("至第 " + next + " 章末", "End of chapter " + next)}</option>
        </optgroup>
      );
    }
  }

  return (
    <div className={"bible-passage-row" + (count > 1 ? " has-badge" : "")}>
      {count > 1 && <span className="bible-passage-badge" aria-label={t("第 " + (index + 1) + " 段", "Passage " + (index + 1))}>{index + 1}</span>}
      <label className="bible-field bible-field-book">
        <span className="bible-field-label">{t("書卷", "Book")}</span>
        <select value={p.bookId} onChange={(e) => go({ bookId: e.target.value, chapter: 1, endChapter: 1, verseFrom: undefined, verseTo: undefined })}>
          <optgroup label={t("舊約", "Old Testament")}>{group("OT")}</optgroup>
          <optgroup label={t("新約", "New Testament")}>{group("NT")}</optgroup>
        </select>
      </label>
      <label className="bible-field">
        <span className="bible-field-label">{t("章", "Chapter")}</span>
        <select value={ch} onChange={(e) => { const c = Number(e.target.value); go({ chapter: c, endChapter: c, verseFrom: undefined, verseTo: undefined }); }}>
          {Array.from({ length: book.chapters }, (_, i) => i + 1).map((n) => <option key={n} value={n}>{n}</option>)}
        </select>
      </label>
      <label className="bible-field">
        <span className="bible-field-label">{t("起節", "From")}</span>
        <select value={p.verseFrom || ""} onChange={(e) => {
          const from = e.target.value ? Number(e.target.value) : undefined;
          if (from == null) { go({ verseFrom: undefined, verseTo: undefined }); return; }
          // Moving the start past the end drags the end along; it never swaps.
          const to = p.endChapter === ch && p.verseTo != null && p.verseTo < from ? from : p.verseTo;
          go({ verseFrom: from, verseTo: p.verseFrom == null ? from : to });
        }}>
          <option value="">{t("整章", "Whole chapter")}</option>
          {fromList.map((n) => <option key={n} value={n}>{n}</option>)}
        </select>
      </label>
      <label className="bible-field bible-field-to">
        <span className="bible-field-label">{t("迄", "To")}</span>
        <select value={toValue} onChange={(e) => {
          const [c, v] = e.target.value.split(":");
          go({ endChapter: Number(c), verseTo: v === "end" ? undefined : Number(v) });
        }}>
          {toOptions}
        </select>
      </label>
      <div className="bible-chapter-step">
        <button type="button" className="bible-btn" disabled={ch <= 1}
          onClick={() => go({ chapter: ch - 1, endChapter: ch - 1, verseFrom: undefined, verseTo: undefined })}>
          <Icon name="chevron-left" size={14} /> {t("上一章", "Previous")}
        </button>
        <button type="button" className="bible-btn" disabled={p.endChapter >= book.chapters}
          onClick={() => go({ chapter: p.endChapter + 1, endChapter: p.endChapter + 1, verseFrom: undefined, verseTo: undefined })}>
          {t("下一章", "Next")} <Icon name="chevron-right" size={14} />
        </button>
        {/* Run on into the next chapter (to its end), or back to this one. */}
        {(next || p.endChapter > ch) && (
          <button type="button" className={"bible-btn bible-span-toggle" + (p.endChapter > ch ? " active" : "")}
            aria-pressed={p.endChapter > ch}
            onClick={() => p.endChapter > ch
              ? go({ endChapter: ch, verseTo: p.verseFrom == null ? undefined : p.verseFrom })
              : go({ endChapter: next, verseTo: undefined })}>
            {p.endChapter > ch
              ? t("只看第 " + ch + " 章", "Chapter " + ch + " only")
              : t("接續第 " + next + " 章", "Continue into " + next)}
          </button>
        )}
        {onRemove && (
          <button type="button" className="bible-btn bible-remove" onClick={onRemove} aria-label={t("移除第 " + (index + 1) + " 段", "Remove passage " + (index + 1))}>
            <Icon name="x" size={13} /> {t("移除", "Remove")}
          </button>
        )}
      </div>
    </div>
  );
}

// ── One passage on screen ──────────────────────────────────────────────
// view "selected": every chosen verse, in full, on one screen.
// view "chapter":  the whole chapter (or both chapters), chosen verses marked.
function biblePassageRows(p, columns, results) {
  const B = window.BIBLE;
  const rows = [];
  let ready = true;
  for (let c = p.chapter; c <= p.endChapter; c++) {
    const nums = new Set();
    const ends = {};
    for (const id of columns) {
      const r = results[id + "|" + p.bookId + "|" + c];
      if (!r) { ready = false; continue; }
      if (r.status !== "ok") continue;
      for (const k of Object.keys(r.verses)) nums.add(Number(k));
      for (const [k, v] of Object.entries(r.rangeEnds)) ends[k] = Math.max(ends[k] || 0, v);
    }
    for (const n of Array.from(nums).sort((a, b) => a - b)) {
      rows.push({ c, n, end: ends[n] || null, key: c + ":" + n, sel: B.inPassage(p, c, n, ends[n]) });
    }
  }
  return { rows, ready };
}

function BiblePassageBlock({ passage, index, multi, columns, results, view, jumpToken, lang }) {
  const B = window.BIBLE;
  const t = (c, e) => (lang === "cht" ? c : e);
  const p = passage;
  const { rows: all, ready } = biblePassageRows(p, columns, results);
  const spans = p.endChapter > p.chapter;
  const marked = p.verseFrom != null; // a verse range was chosen, not whole chapters
  const rows = view === "chapter" ? all : all.filter((r) => r.sel);
  const target = marked ? all.find((r) => r.sel) : null;

  const segment = B.refToHash(p);

  // Whole-chapter view: bring the chosen verse into view, once per jump.
  const targetRef = React.useRef(null);
  const scrolledFor = React.useRef("");
  React.useEffect(() => {
    if (index !== 0 || view !== "chapter" || !ready || !targetRef.current) return;
    const key = segment + "|" + jumpToken;
    if (scrolledFor.current === key) return;
    scrolledFor.current = key;
    targetRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
  }, [view, ready, segment, jumpToken]);

  const fumsKey = ready ? columns.filter((id) => B.TRANSLATION_BY_ID[id].api).map((id) => {
    const toks = [];
    for (let c = p.chapter; c <= p.endChapter; c++) {
      const r = results[id + "|" + p.bookId + "|" + c];
      if (r && r.fumsToken) toks.push(r.fumsToken);
    }
    return toks.join(",");
  }).join(",") : "";
  React.useEffect(() => { if (fumsKey) bibleTrackFums(fumsKey.split(",").filter(Boolean)); }, [fumsKey]);

  const failed = columns.filter((id) => {
    for (let c = p.chapter; c <= p.endChapter; c++) {
      const r = results[id + "|" + p.bookId + "|" + c];
      if (r && r.status === "error") return true;
    }
    return false;
  });

  const out = [];
  let lastChapter = null;
  for (const r of rows) {
    if (spans && r.c !== lastChapter) {
      out.push(
        <div className="bible-row bible-chapter-row" key={"ch" + r.c}>
          <div className="bible-chapter-label">{t(bibleBookName(p.bookId, lang) + " 第 " + r.c + " 章", bibleBookName(p.bookId, lang) + " — Chapter " + r.c)}</div>
        </div>
      );
    }
    lastChapter = r.c;
    // Marking only means something when the rest of the chapter is around it.
    const isTarget = view === "chapter" && target && r.key === target.key;
    const cls = "bible-row" + (isTarget ? " is-target" : view === "chapter" && marked && r.sel ? " is-sel" : "");
    out.push(
      <div className={cls} key={r.key} ref={isTarget ? targetRef : undefined}>
        <div className="bible-vnum">{r.n}</div>
        {columns.map((id, i) => {
          const res = results[id + "|" + p.bookId + "|" + r.c];
          const text = res && res.status === "ok" ? res.verses[r.n] : undefined;
          const end = res && res.rangeEnds[r.n];
          return (
            <div className={"bible-cell bible-col-" + (i + 1) + (text ? "" : " bible-cell-empty")} key={id}
              data-label={B.TRANSLATION_BY_ID[id].short} lang={bibleTextLang(id)}>
              {end ? <span className="bible-range" lang="en">{r.n}–{end}</span> : null}
              {text || "—"}
            </div>
          );
        })}
      </div>
    );
  }

  return (
    <section className={"bible-block" + (ready ? "" : " is-loading")} aria-label={biblePassageLabel(p, lang)}>
      {multi && (
        <h3 className="bible-block-title">
          <span className="bible-passage-badge">{index + 1}</span> {biblePassageLabel(p, lang)}
        </h3>
      )}
      {failed.length > 0 && ready && (
        <div className="bible-note bible-note-warn">
          {t("未能載入：", "Could not load: ")}{failed.map((id) => bibleTranslationName(id, lang)).join("、")}
          {t("。請檢查網絡後再試。", ". Check your connection and try again.")}
        </div>
      )}
      <div className={"bible-reader" + (view === "chapter" ? " is-chapter" : "")} style={{ "--cols": columns.length }}>
        <div className="bible-row bible-head-row">
          <div className="bible-vnum">{t("節", "V")}</div>
          {columns.map((id, i) => (
            <div className={"bible-cell bible-col-" + (i + 1)} key={id}>
              <span className="bible-col-title" lang={lang === "cht" ? bibleTextLang(id) : "en"}>{bibleTranslationName(id, lang)}</span>
              <span className="bible-col-sub">{B.TRANSLATION_BY_ID[id].short}</span>
            </div>
          ))}
        </div>
        {ready && rows.length === 0 && (
          <div className="bible-row">
            <div className="bible-vnum">—</div>
            <div className="bible-cell bible-cell-empty" style={{ gridColumn: "2 / -1" }}>{t("此範圍沒有經文。", "No verses in this range.")}</div>
          </div>
        )}
        {out}
      </div>
      <BibleRights ids={columns} lang={lang} numbered />
    </section>
  );
}

// ── Translations & copyright page (#bible/about) ───────────────────────
function BibleAbout({ lang, apiOk }) {
  const B = window.BIBLE;
  const t = (c, e) => (lang === "cht" ? c : e);
  const gbi = B.TRANSLATIONS.filter((tr) => tr.gbi);
  const pd = B.TRANSLATIONS.filter((tr) => tr.pd);
  // Only the API.Bible translations this site's key may use.
  const apiTr = B.TRANSLATIONS.filter((tr) => tr.api && apiOk && apiOk[tr.id]);
  return (
    <div className="bible-about">
      <a className="bible-btn" href="#bible"><Icon name="arrow-left" size={14} /> {t("返回研經", "Back to the reader")}</a>
      <h2 className="about-title">{t("譯本與版權", "Translations & copyright")}</h2>
      <p className="bible-about-lead">
        {t("研經工具僅供非商業研經使用：沒有廣告、收費或訂閱。經文按來源原樣顯示，不作任何修改。",
           "The study tool is for non-commercial Bible study only — no advertising, fees or subscriptions. Scripture is shown exactly as supplied, without alteration.")}
      </p>
      <h3 className="bible-about-h">{t("中文譯本", "Chinese translations")}</h3>
      <p className="bible-about-p">
        {t("以下四個中文譯本的版權屬全球聖經促進會（Global Bible Initiative）所有，經其書面同意在本非商業研經工具中使用，經文取自 Digital Bible Library 的官方資料。本工具無權轉授權，請勿轉載或作其他用途。",
           "The four Chinese editions below are copyrighted by Global Bible Initiative and are used in this non-commercial study tool with its written permission; the text comes from the official Digital Bible Library packages. This site cannot sublicense them — please do not copy them for other uses.")}
      </p>
      <div className="bible-about-list">
        {gbi.map((tr) => (
          <div className="bible-about-card" key={tr.id}>
            <div className="bible-about-name" lang={lang === "cht" ? bibleTextLang(tr.id) : "en"}>{lang === "cht" ? tr.cht : tr.eng}</div>
            <BibleRights ids={[tr.id]} lang={lang} />
          </div>
        ))}
      </div>
      <h3 className="bible-about-h">{t("公有領域英文譯本", "Public-domain English translations")}</h3>
      <p className="bible-about-p">
        {t("以下英文譯本屬公有領域，經文取自 eBible.org 的原始檔案，只刪去註腳與標題，經文本身不作改動。",
           "The English translations below are in the public domain. The text comes from eBible.org's source files; footnotes and headings are left out and the verses themselves are not changed.")}
      </p>
      <div className="bible-about-list">
        {pd.map((tr) => (
          <div className="bible-about-card" key={tr.id}>
            <div className="bible-about-name" lang={lang === "cht" ? "zh-Hant" : "en"}>{lang === "cht" ? tr.cht : tr.eng}</div>
            <BibleRights ids={[tr.id]} lang={lang} />
          </div>
        ))}
      </div>
      {apiTr.length > 0 && <>
      <h3 className="bible-about-h">{t("API.Bible 英文譯本", "English translations from API.Bible")}</h3>
      <p className="bible-about-p">
        {t("以下英文譯本經 API.Bible 即時提供，按其非商業授權使用，版權屬各出版者所有。只會提供本網站獲授權使用的譯本。顯示這些經文時，本網站按 API.Bible 的要求以其 FUMS 系統回報經文的瀏覽次數（匿名）。",
           "The English translations below are supplied live by API.Bible under its non-commercial licence; copyright belongs to each publisher. Only translations this site is licensed to use are offered. When their text is shown, this site reports the view to API.Bible's Fair Use Management System (FUMS), anonymously, as its licence requires.")}
      </p>
      <div className="bible-about-list">
        {apiTr.map((tr) => (
          <div className="bible-about-card" key={tr.id}>
            <div className="bible-about-name" lang="en">{B.API_RIGHTS[tr.id].name}</div>
            <BibleRights ids={[tr.id]} lang={lang} />
          </div>
        ))}
      </div>
      </>}
      <p className="bible-about-p">
        {t("研經工具只提供以上已獲授權的譯本。每日靜思文章內另引用的經文，說明見「免責聲明」。",
           "The study tool offers only the licensed translations above. Scripture quoted inside the daily devotionals is covered by the Disclaimer.")}
      </p>
    </div>
  );
}

// ── Section root (#bible, #bible/about, #bible/<Book>/<ch>[/<v>…][;<passage 2>]) ─
// `searchRequest` = { text, token } from the site header's search box, which
// in this section takes a reference ("約 3:16", "John 3:16-4:3",
// "Isa 53; Acts 8:26-40") or a keyword.
function BibleView({ lang, searchRequest }) {
  const B = window.BIBLE;
  const t = (c, e) => (lang === "cht" ? c : e);
  const initial = React.useMemo(() => B.parseBibleHash(window.location.hash) || { page: "reader", passages: null }, []);

  const [page, setPage] = React.useState(initial.page);
  const [prefs, setPrefs] = React.useState(() => {
    const saved = bibleLoadPrefs();
    const next = initial.passages ? { ...saved, passages: initial.passages } : saved;
    // Arrived from a "study this verse" link: show those verses, not the chapter.
    try {
      if (sessionStorage.getItem(BIBLE_OPEN_SELECTED_KEY)) {
        sessionStorage.removeItem(BIBLE_OPEN_SELECTED_KEY);
        // The verse opens beside the language's own default pair (和合本 | NIV
        // in Chinese, NIV | 和合本 in English), not whatever was picked before.
        return { ...next, view: "selected", columnsChosen: false };
      }
    } catch (e) { /* storage unavailable */ }
    return next;
  });
  // Which API translations the server can serve (null while asking).
  const [apiOk, setApiOk] = React.useState(null);
  React.useEffect(() => { BibleStore.apiStatus().then((st) => setApiOk(st)); }, []);
  const apiAvailable = (id) => !B.TRANSLATION_BY_ID[id].api || apiOk === null || !!(apiOk && apiOk[id]);
  // Columns on screen: the reader's own choice, or the interface language's
  // default pair; an API translation the server cannot serve is left out.
  const columns = React.useMemo(() => {
    const base = prefs.columnsChosen ? prefs.columns : B.DEFAULT_COLUMNS_BY_LANG[lang === "cht" ? "cht" : "eng"];
    const usable = base.filter(apiAvailable);
    if (usable.length === base.length) return base;
    if (prefs.columnsChosen) return usable.length ? usable : B.DEFAULT_COLUMNS.slice();
    // Language default without the API: the KJV takes the NIV's place.
    return [...new Set(base.map((id) => (apiAvailable(id) ? id : "kjv")))];
  }, [prefs.columnsChosen, prefs.columns.join(","), lang, apiOk]);
  const pickable = B.TRANSLATIONS.filter((tr) => apiAvailable(tr.id)).map((tr) => tr.id);
  const [results, setResults] = React.useState({});
  const [jumpToken, setJumpToken] = React.useState(0);
  const [search, setSearch] = React.useState(null); // { text, busy, hits, message }
  const [notice, setNotice] = React.useState(null);
  const update = (patch) => setPrefs((prev) => ({ ...prev, ...patch }));
  const passagesKey = B.refToHash(prefs.passages);

  // The address bar always names what is on screen, so any view can be
  // bookmarked or shared. replaceState, not location.hash: paging through
  // verses should not pile up Back-button stops (and it fires no hashchange,
  // so this cannot loop with the listener below).
  React.useEffect(() => {
    bibleSavePrefs(prefs);
    const want = "#" + (page === "about" ? "bible/about" : passagesKey);
    if (window.location.hash !== want) {
      try { window.history.replaceState(null, "", want); } catch (e) { /* e.g. sandboxed preview */ }
    }
  }, [prefs, page]);

  // Links into the section from elsewhere (a day's "study this verse", the
  // copyright page link, a pasted URL) arrive as a hash change.
  React.useEffect(() => {
    const onHash = () => {
      const p = B.parseBibleHash(window.location.hash);
      if (!p) return; // leaving the section — app.jsx switches view
      setPage(p.page);
      if (p.passages) {
        setPrefs((prev) => ({ ...prev, passages: p.passages }));
        setSearch(null);
        setNotice(null);
        setJumpToken((n) => n + 1);
      }
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Every chapter of every passage, in every chosen translation.
  const columnsKey = columns.join(",");
  React.useEffect(() => {
    let cancelled = false;
    const jobs = [];
    for (const p of prefs.passages) {
      for (let c = p.chapter; c <= p.endChapter; c++) {
        for (const id of columns) jobs.push([id, p.bookId, c]);
      }
    }
    Promise.all(jobs.map(([id, b, c]) => BibleStore.getChapter(id, b, c))).then((res) => {
      if (cancelled) return;
      const next = {};
      res.forEach((r, i) => { next[jobs[i].join("|")] = r; });
      setResults(next);
    });
    return () => { cancelled = true; };
  }, [columnsKey, passagesKey]);

  const verseCount = (bookId) => (c) => BibleStore.verseCount(columns, bookId, c);

  function showPassages(passages, info) {
    setPage("reader");
    update({ passages });
    setJumpToken((n) => n + 1);
    setNotice(info && (info.dropped || info.clamped)
      ? t("一次最多顯示兩段經文，每段最多兩章；超出的部分沒有顯示。", "Up to two passages are shown at a time, each at most two chapters long; the rest was left out.")
      : null);
  }

  // Header search: references jump straight there; anything else is a
  // keyword search of the translations currently on screen.
  const searchToken = searchRequest ? searchRequest.token : 0;
  React.useEffect(() => {
    if (!searchToken) return;
    const text = String(searchRequest.text || "").trim();
    if (!text) { setSearch(null); return; }
    const parsed = B.parsePassages(text);
    if (parsed) {
      showPassages(parsed.passages, parsed);
      setSearch(null);
      return;
    }
    setPage("reader");
    if (text.length < 2) {
      setSearch({ text, busy: false, hits: [], message: t("請輸入經文出處（如「約 3:16」）或最少兩個字的關鍵字。", "Enter a reference (such as John 3:16) or a keyword of at least two characters.") });
      return;
    }
    let cancelled = false;
    setSearch({ text, busy: true, hits: [], message: null });
    BibleStore.search(text, columns, 60).then((hits) => {
      if (!cancelled) setSearch({ text, busy: false, hits, message: null });
    });
    return () => { cancelled = true; };
  }, [searchToken]);

  const setPassage = (i, p) => { const list = prefs.passages.slice(); list[i] = p; update({ passages: list }); setNotice(null); setSearch(null); };
  const removePassage = (i) => update({ passages: prefs.passages.filter((_, k) => k !== i) });
  // Second passage: start at the first book of the chosen testament; the
  // book list in its row then picks any book. Old + Old, New + New and
  // Old + New are all fine.
  const addPassage = (testament) => {
    const bookId = testament === "OT" ? "Gen" : "Matt";
    update({ passages: [prefs.passages[0], { bookId, chapter: 1, endChapter: 1 }] });
    setNotice(null);
  };
  const wideAvailable = columns.length >= 3;
  const wide = wideAvailable && prefs.wide;

  return (
    <div className={"page bible-page" + (wide ? " bible-wide" : "")}>
      <div className="about-eyebrow">
        <span className="line"></span>
        <Icon name="book" size={12} />
        <span>{t("聖經對照研讀", "Parallel Bible Study")}</span>
        <Icon name="book" size={12} />
        <span className="line"></span>
      </div>

      {page === "about" ? <BibleAbout lang={lang} apiOk={apiOk} /> : (
        <>
          <h2 className={"bible-title" + (prefs.passages.length > 1 ? " is-two" : "")}>
            {prefs.passages.map((p) => biblePassageLabel(p, lang)).join(lang === "cht" ? "；" : "; ")}
          </h2>
          <p className="bible-hint">
            {t("在頁首搜尋列輸入經文出處或關鍵字後按 Enter，例如「約 3:16」「約 3:16-4:3」「賽 53；徒 8:26-40」。",
               "Type a reference or keyword in the search box above and press Enter — John 3:16, John 3:16-4:3, Isa 53; Acts 8:26-40.")}
          </p>
          {notice && <div className="bible-note bible-note-info">{notice}</div>}

          <div className="bible-controls">
            <BiblePicker columns={columns} available={pickable} lang={lang} onChange={(next) => update({ columns: next, columnsChosen: true })} />
            <div className="bible-passages">
              {prefs.passages.map((p, i) => (
                <BiblePassageEditor key={i} passage={p} index={i} count={prefs.passages.length} lang={lang}
                  verseCount={verseCount(p.bookId)} onChange={(np) => setPassage(i, np)}
                  onRemove={i > 0 ? () => removePassage(i) : null} />
              ))}
              {prefs.passages.length < B.MAX_PASSAGES && (
                <div className="bible-add-row">
                  <span className="bible-field-label">{t("第二段經文", "Second passage")}</span>
                  <button type="button" className="bible-add-passage" onClick={() => addPassage("OT")}>
                    ＋ {t("舊約經文", "Old Testament")}
                  </button>
                  <button type="button" className="bible-add-passage" onClick={() => addPassage("NT")}>
                    ＋ {t("新約經文", "New Testament")}
                  </button>
                  <span className="bible-add-hint">{t("最多兩段，可跨書卷；每段可接續到下一章", "Up to two passages, from any books; each can run into the next chapter")}</span>
                </div>
              )}
            </div>
            <div className="bible-display">
              <span className="bible-field-label">{t("顯示", "Show")}</span>
              <div className="bible-toggle" role="group" aria-label={t("顯示方式", "Display")}>
                <button type="button" className={prefs.view === "selected" ? "active" : ""} aria-pressed={prefs.view === "selected"}
                  onClick={() => update({ view: "selected" })}>
                  {t("所選經文", "Selected verses")}
                </button>
                <button type="button" className={prefs.view === "chapter" ? "active" : ""} aria-pressed={prefs.view === "chapter"}
                  onClick={() => { update({ view: "chapter" }); setJumpToken((n) => n + 1); }}>
                  {t("全章", "Whole chapter")}
                </button>
              </div>
              {wideAvailable && (
                <button type="button" className={"bible-wide-toggle" + (wide ? " active" : "")} aria-pressed={wide}
                  onClick={() => update({ wide: !prefs.wide })}
                  title={t("三至四個譯本時，把閱讀區拉闊", "Use more of the screen for three or four translations")}>
                  <span aria-hidden="true">⇔</span> {t("寬版", "Wide")}
                </button>
              )}
            </div>
          </div>

          {search && (
            <div className="bible-search">
              <div className="bible-search-head">
                <span>
                  {search.busy
                    ? t("正在搜尋「" + search.text + "」…", "Searching for “" + search.text + "”…")
                    : search.message
                      ? search.message
                      : search.hits.length
                        ? t("「" + search.text + "」：找到 " + search.hits.length + " 節" + (search.hits.length >= 60 ? "（只顯示首 60 節）" : ""),
                            search.hits.length + (search.hits.length >= 60 ? "+" : "") + " verses for “" + search.text + "”" + (search.hits.length >= 60 ? " (first 60 shown)" : ""))
                        : t("在所選譯本找不到「" + search.text + "」。", "No match for “" + search.text + "” in the selected translations.")}
                </span>
                <button type="button" className="bible-btn" onClick={() => setSearch(null)}>
                  <Icon name="x" size={13} /> {t("關閉", "Close")}
                </button>
              </div>
              {search.hits.length > 0 && (
                <>
                  <div className="bible-hits">
                    {search.hits.map((h, i) => (
                      <button type="button" className="bible-hit" key={i}
                        onClick={() => { showPassages([{ bookId: h.bookId, chapter: h.chapter, endChapter: h.chapter, verseFrom: h.verse, verseTo: h.verse }]); setSearch(null); window.scrollTo({ top: 0, behavior: "smooth" }); }}>
                        <span className="bible-hit-ref">
                          {bibleBookName(h.bookId, lang)} {h.chapter}:{h.verse}
                          <span className="bible-hit-ver">{B.TRANSLATION_BY_ID[h.tid].short}</span>
                        </span>
                        <span className="bible-hit-text" lang={bibleTextLang(h.tid)}>{h.text}</span>
                      </button>
                    ))}
                  </div>
                  <BibleRights ids={columns.filter((id) => search.hits.some((h) => h.tid === id))} lang={lang} />
                </>
              )}
            </div>
          )}

          {prefs.passages.map((p, i) => (
            <BiblePassageBlock key={i + "|" + B.refToHash(p)} passage={p} index={i} multi={prefs.passages.length > 1}
              columns={columns} results={results} view={prefs.view} jumpToken={jumpToken} lang={lang} />
          ))}

          <p className="bible-footnote">
            {t("本研經工具僅供非商業研經使用，經文按來源原樣顯示。", "This study tool is for non-commercial Bible study only; Scripture is shown exactly as supplied.")}
            {" "}
            <a href="#bible/about">{t("譯本與版權 →", "Translations & copyright →")}</a>
          </p>
        </>
      )}
    </div>
  );
}

// ── Home page: the day's verse, one translation at a time ──────────────
// The reference comes from the day record (days.js); the text comes only from
// the local editions in assets/bible/ (the four GBI editions in Chinese, the
// four public-domain Bibles in English) and, in English, the NIV from
// API.Bible when the key allows it — each shown with its notice. The
// devotional's own 和合本 and NIV quotations are deliberately NOT used here. Translations change every 5 seconds;
// the reader can also pick one or step through days.
// In English the NIV comes first when API.Bible can serve it (its notice is
// shown and the view is reported to FUMS like anywhere else).
const VOTD_ORDER_BY_LANG = {
  cht: ["cuvmpt", "csbt", "cuvmps", "csbs"],
  eng: ["niv", "kjv", "web", "asv", "bbe"],
};
const VOTD_INTERVAL_MS = 5000;
const VOTD_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// Short date for the panel's date button, so it stays on one line on a phone:
// "19 Nov 2026 · Thu" / "2026年11月19日（四）".
function votdShortDate(day, lang) {
  const [y, m, d] = String(day.iso).split("-").map(Number);
  if (!y || !m || !d) return lang === "cht" ? day.date_cht : day.date_eng;
  return lang === "cht"
    ? `${y}年${m}月${d}日` + (day.weekday_short_cht ? `（${day.weekday_short_cht}）` : "")
    : `${d} ${VOTD_MONTHS[m - 1]} ${y}` + (day.weekday_short_eng ? ` · ${day.weekday_short_eng}` : "");
}

function VerseOfDay({ lang, onOpen }) {
  const B = window.BIBLE;
  const days = window.DAYS || [];
  const t = (c, e) => (lang === "cht" ? c : e);
  const [dayIdx, setDayIdx] = React.useState(0); // 0 = newest; days.js is newest-first
  const day = days[dayIdx];
  const ref = React.useMemo(
    () => (day ? B.parseReference(day.scripture.ref_eng) || B.parseReference(day.scripture.ref_cht) : null),
    [day && day.iso]
  );

  const [apiOk, setApiOk] = React.useState(null);
  React.useEffect(() => { BibleStore.apiStatus().then((st) => setApiOk(st || {})); }, []);

  const slides = React.useMemo(() => {
    if (!day) return [];
    if (!ref) return [];
    return VOTD_ORDER_BY_LANG[lang === "cht" ? "cht" : "eng"]
      .filter((key) => !B.TRANSLATION_BY_ID[key].api || !!(apiOk && apiOk[key]))
      .map((key) => {
      const tr = B.TRANSLATION_BY_ID[key];
      return { key, tid: key, label: tr.short.replace(/\s+/g, ""), name: lang === "cht" ? tr.cht : tr.eng, textLang: bibleTextLang(key) };
    });
  }, [day && day.iso, lang, !!ref, apiOk]);

  const [slideIdx, setSlideIdx] = React.useState(0);
  const [passages, setPassages] = React.useState({}); // "<iso>|<tid>" → [{c,n,end,text}] | null
  const reduceMotion = React.useMemo(
    () => !!(window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches), []);
  const [hover, setHover] = React.useState(false);

  React.useEffect(() => { setSlideIdx(0); }, [day && day.iso, lang]);

  const idx = slides.length ? slideIdx % slides.length : 0;
  const slide = slides[idx];
  const pKey = (s) => (day ? day.iso : "") + "|" + s.tid;

  // Load the slide on screen and the one after it, so a rotation never lands
  // on a blank. Each book file is fetched once and cached by BibleStore.
  React.useEffect(() => {
    if (!day || !ref || !slides.length) return;
    let cancelled = false;
    [slides[idx], slides[(idx + 1) % slides.length]].forEach((s) => {
      if (!s || !s.tid || pKey(s) in passages) return;
      BibleStore.getPassage(s.tid, ref).then((p) => {
        if (!cancelled) setPassages((prev) => (pKey(s) in prev ? prev : { ...prev, [pKey(s)]: p }));
      });
    });
    return () => { cancelled = true; };
  }, [day && day.iso, idx, slides.length, lang]);

  const passage = slide && slide.tid ? passages[pKey(slide)] : undefined;
  React.useEffect(() => {
    if (slide && passage && B.TRANSLATION_BY_ID[slide.tid].api) bibleTrackFums(BibleStore.apiTokens(slide.tid, ref));
  }, [slide && slide.tid, passage, day && day.iso]);
  const ready = !!slide && passage !== undefined;
  const missing = !!slide && slide.tid && passage === null;
  const textLength = (passage || []).reduce((n, v) => n + v.text.length, 0);

  // Rotation: a new translation every 5 seconds, once its text is in. Holds
  // while a mouse pointer rests on the panel; off for readers who ask for
  // reduced motion. A translation without the verse is passed over at once.
  React.useEffect(() => {
    if (reduceMotion || hover || slides.length < 2 || !ready) return;
    const ms = missing ? 600 : VOTD_INTERVAL_MS;
    const timer = setTimeout(() => setSlideIdx((i) => (i + 1) % slides.length), ms);
    return () => clearTimeout(timer);
  }, [hover, idx, ready, missing, slides.length]);

  if (!day || !slide) return null;

  const older = days[dayIdx + 1];
  const newer = days[dayIdx - 1];
  const refText = biblePassageLabel(ref, lang);
  const sizeClass = textLength > 150 ? " votd-long" : textLength > 80 ? " votd-mid" : "";
  const step = (d) => setSlideIdx((idx + d + slides.length) % slides.length);

  return (
    <section className="votd" aria-label={t("今日經文", "Verse of the day")}
      onPointerEnter={(e) => { if (e.pointerType === "mouse") setHover(true); }}
      onPointerLeave={() => setHover(false)}>
      <div className="votd-top">
        <div className="votd-eyebrow">
          ✝ {dayIdx === 0 ? t("今日經文", "Today’s Scripture") : t("當日經文", "Scripture of the day")}
          <span className="votd-eyebrow-sub">{t("多譯本對照", "in many translations")}</span>
        </div>
        <div className="votd-datenav">
          <button type="button" className="votd-arrow" disabled={!older} onClick={() => setDayIdx(dayIdx + 1)}
            aria-label={t("上一日", "Previous day")} title={t("上一日", "Previous day")}>
            <Icon name="chevron-left" size={16} />
          </button>
          <button type="button" className="votd-date" onClick={() => onOpen && onOpen(day.iso)}
            title={t("閱讀當日靜思", "Read that day’s devotional")}>
            <Icon name="calendar" size={13} /> {votdShortDate(day, lang)}
          </button>
          <button type="button" className="votd-arrow" disabled={!newer} onClick={() => setDayIdx(dayIdx - 1)}
            aria-label={t("下一日", "Next day")} title={t("下一日", "Next day")}>
            <Icon name="chevron-right" size={16} />
          </button>
          {dayIdx > 0 && (
            <button type="button" className="votd-today" onClick={() => setDayIdx(0)}>{t("回到今日", "Today")}</button>
          )}
        </div>
      </div>

      <div className="votd-stage">
        <button type="button" className="votd-side votd-side-prev" onClick={() => step(-1)}
          aria-label={t("上一個譯本", "Previous translation")}><Icon name="chevron-left" size={20} /></button>
        <div className="votd-body" aria-live="polite">
          <div className="votd-version" key={"v" + slide.key}>
            <span className="votd-version-tag">{slide.label}</span>
            <span className="votd-version-name" lang={lang === "cht" ? slide.textLang : "en"}>{slide.name}</span>
          </div>
          <blockquote className={"votd-verse" + sizeClass} key={day.iso + slide.key + (ready ? "r" : "l")} lang={slide.textLang}>
            {!ready ? <span className="votd-loading">{t("載入經文中…", "Loading…")}</span>
              : missing ? <span className="votd-loading">{t("此譯本沒有這節經文。", "This translation has no verse here.")}</span>
              : passage.map((v) => (
                  <React.Fragment key={v.c + ":" + v.n}>
                    {passage.length > 1 || v.end ? <sup className="votd-vnum">{(ref.endChapter > ref.chapter ? v.c + ":" : "") + (v.end ? v.n + "–" + v.end : v.n)}</sup> : null}
                    {v.text}
                  </React.Fragment>
                ))}
          </blockquote>
          <div className="votd-ref">— {refText}</div>
        </div>
        <button type="button" className="votd-side votd-side-next" onClick={() => step(1)}
          aria-label={t("下一個譯本", "Next translation")}><Icon name="chevron-right" size={20} /></button>
      </div>

      <div className="votd-chips" role="tablist" aria-label={t("譯本", "Translations")}>
        {slides.map((s, i) => (
          <button type="button" role="tab" key={s.key} aria-selected={i === idx} title={s.name}
            className={"votd-chip" + (i === idx ? " active" : "")}
            onClick={() => setSlideIdx(i)}>
            {s.label}
          </button>
        ))}
      </div>

      <div className="votd-foot">
        <div className="votd-rights">
          {slide.tid ? <BibleRights ids={[slide.tid]} lang={lang} /> : null}
        </div>
        <div className="votd-actions">
          {ref && <a className="votd-link" href={"#" + B.refToHash(ref)} onClick={bibleMarkStudyLink}><Icon name="book" size={14} /> {t("對照研讀這節經文", "Study this verse in parallel")}</a>}
          <button type="button" className="votd-link" onClick={() => onOpen && onOpen(day.iso)}>
            {t("閱讀當日靜思", "Read the devotional")} <Icon name="arrow-right" size={14} />
          </button>
        </div>
      </div>
    </section>
  );
}
