// Bible tab: full WEB Bible (66 books — bundled chapters open instantly, the
// rest load once via /api/bible and cache on-device) + highlighting & notes.
(function () {
  const { Icon } = window;
  const { useState, useEffect } = React;
  const { Screen, RoundBtn, safeTop } = window.NLUI;
  const D = window.NLData;

  const HL = {
    leaf:  'var(--nl-leaf-200)',
    wheat: 'var(--nl-wheat-300)',
    clay:  'var(--nl-clay-100)',
    sky:   'var(--nl-navy-200)',
  };

  // Verse lookup that also checks the on-device chapter cache.
  function chapterVerses(key) {
    if (D.bibleText[key]) return D.bibleText[key];
    try {
      const ref = D.parseRef(key);
      if (!ref) return null;
      const hit = localStorage.getItem(`nlc_bible:${ref.book}:${ref.chapter}`);
      if (hit) { const d = JSON.parse(hit); D.bibleText[key] = d.verses; return d.verses; }
    } catch (e) {}
    return null;
  }

  // This week's chapters, from real sermon scripture references.
  function weekChapters() {
    const keys = [];
    for (const s of D.sermons.slice(0, 8)) {
      const ref = D.parseRef(s.scripture);
      if (ref && !keys.includes(ref.key)) keys.push(ref.key);
      if (keys.length >= 4) break;
    }
    return keys.length ? keys : ['John 1', 'Psalms 23'];
  }

  // ---- Bible home ---------------------------------------------------------
  function Bible({ nav, store }) {
    const last = store.lastChapter || 'John 1';
    const hlCount = Object.values(store.highlights).reduce((a, c) => a + Object.keys(c).length, 0);
    const noteCount = Object.keys(store.verseNotes).length;
    return (
      <Screen header={{ variant: 'large', title: 'Bible', right: <RoundBtn name="search" onClick={() => nav.push('search')} /> }}>
        {/* continue */}
        <div style={{ padding: '0 20px 18px' }}>
          <button onClick={() => nav.push('reader', { chapter: last })} style={{ width: '100%', textAlign: 'left', cursor: 'pointer',
            border: 0, borderRadius: 18, overflow: 'hidden', padding: 22, position: 'relative',
            background: 'linear-gradient(150deg, var(--nl-navy-700), var(--nl-navy-900))' }}>
            <div style={{ position: 'absolute', top: -34, right: -6, fontFamily: 'var(--nl-font-serif)', fontWeight: 700,
              fontSize: 170, lineHeight: 1, color: 'rgba(145,202,65,0.12)' }}>”</div>
            <div className="nl-eyebrow" style={{ color: 'var(--nl-leaf-500)' }}>Continue reading</div>
            <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: '#fff', margin: '10px 0 2px' }}>{last}</div>
            <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13, color: 'rgba(255,255,255,0.65)' }}>World English Bible</div>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 16, background: 'var(--nl-leaf-600)',
              color: 'var(--nl-navy-900)', borderRadius: 999, padding: '8px 16px', fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 13 }}>
              <Icon name="bookOpen" size={16} /> Open
            </div>
          </button>
        </div>

        {/* my bible */}
        <div style={{ padding: '0 20px 24px', display: 'flex', gap: 12 }}>
          <button onClick={() => nav.push('highlights')} style={{ flex: 1, cursor: 'pointer', textAlign: 'left',
            background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderRadius: 14, padding: 16 }}>
            <Icon name="highlighter" size={22} style={{ color: 'var(--nl-leaf-700)' }} />
            <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 22, color: 'var(--nl-navy-900)', marginTop: 8 }}>{hlCount}</div>
            <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-500)' }}>Highlights</div>
          </button>
          <button onClick={() => nav.push('highlights')} style={{ flex: 1, cursor: 'pointer', textAlign: 'left',
            background: 'var(--nl-white)', border: '1px solid var(--nl-border)', borderRadius: 14, padding: 16 }}>
            <Icon name="note" size={22} style={{ color: 'var(--nl-clay-700)' }} />
            <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 22, color: 'var(--nl-navy-900)', marginTop: 8 }}>{noteCount}</div>
            <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12.5, color: 'var(--nl-ink-500)' }}>Notes</div>
          </button>
        </div>

        {/* read along with this week's messages */}
        <div style={{ padding: '0 20px 8px' }}>
          <div className="nl-eyebrow" style={{ marginBottom: 12 }}>Read along with this week</div>
          <div style={{ display: 'flex', gap: 10, overflowX: 'auto', scrollbarWidth: 'none', marginBottom: 24 }}>
            {weekChapters().map(c => (
              <button key={c} onClick={() => nav.push('reader', { chapter: c })} style={{ flexShrink: 0, cursor: 'pointer',
                background: 'var(--nl-wheat-100)', border: '1px solid var(--nl-wheat-300)', borderRadius: 12, padding: '14px 18px', textAlign: 'left' }}>
                <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 17, color: 'var(--nl-navy-900)', whiteSpace: 'nowrap' }}>{c}</div>
                <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 11.5, color: 'var(--nl-wheat-900)', marginTop: 2 }}>WEB</div>
              </button>
            ))}
          </div>
        </div>

        {/* all 66 books */}
        <div style={{ padding: '0 20px' }}>
          <h3 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 19, color: 'var(--nl-navy-900)', margin: '0 0 4px' }}>Books</h3>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0,
          background: 'var(--nl-white)', margin: '8px 16px 0', borderRadius: 14, border: '1px solid var(--nl-border)', overflow: 'hidden' }}>
          {D.BOOKS.map(([b, chapters], i) => (
            <button key={b} onClick={() => nav.push('reader', { chapter: `${b} 1` })}
              style={{ textAlign: 'left', cursor: 'pointer', background: 'none', border: 0, padding: '13px 14px',
                borderBottom: i < D.BOOKS.length - 2 ? '1px solid var(--nl-divider)' : 0,
                borderRight: i % 2 === 0 ? '1px solid var(--nl-divider)' : 0,
                fontFamily: 'var(--nl-font-sans)', fontSize: 15, color: 'var(--nl-navy-900)',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6 }}>
              <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{b}</span>
              <span style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 11.5, color: 'var(--nl-ink-400)', flexShrink: 0 }}>{chapters}</span>
            </button>
          ))}
        </div>
        <p style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 12, color: 'var(--nl-ink-400)', textAlign: 'center', padding: '16px 30px 0' }}>
          World English Bible · chapters save to your device as you read
        </p>
      </Screen>
    );
  }

  // ---- Reader -------------------------------------------------------------
  function Reader({ nav, store, params }) {
    const [chapter, setChapter] = useState(params.chapter || store.lastChapter || 'John 1');
    const [size, setSize] = useState(18);
    const [sel, setSel] = useState(null);
    const [noteDraft, setNoteDraft] = useState('');
    const [verses, setVerses] = useState(() => chapterVerses(chapter));
    const [loadErr, setLoadErr] = useState(null);
    const [picker, setPicker] = useState(null); // null | 'books' | '<book name>'

    const ref = D.parseRef(chapter);
    const book = ref ? D.BOOKS.find(([b]) => b === ref.book) : null;
    const chapterCount = book ? book[1] : 1;

    useEffect(() => { store.setLastChapter(chapter); }, [chapter]);
    useEffect(() => {
      const have = chapterVerses(chapter);
      setVerses(have);
      setLoadErr(null);
      if (!have && ref) {
        window.NLApi.bible(ref.book, ref.chapter)
          .then(d => { D.bibleText[chapter] = d.verses; setVerses(d.verses); })
          .catch(() => setLoadErr(D.mode === 'live'
            ? 'Could not load this chapter. Check your connection and try again.'
            : 'Full Bible loads once the app is connected to the church backend. John 1 and Psalm 23 are available to preview.'));
      }
    }, [chapter]);

    const go = (ch) => { setSel(null); setChapter(ch); };
    const openSheet = (n) => { setSel(n); setNoteDraft(store.verseNotes[`${chapter}:${n}`] || ''); };
    const close = () => setSel(null);
    const hl = store.highlights[chapter] || {};

    return (
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: 'var(--nl-paper)' }}>
        {/* header */}
        <div style={{ paddingTop: safeTop(8), background: 'var(--nl-paper)', borderBottom: '1px solid var(--nl-divider)', flexShrink: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '4px 16px 10px' }}>
            <RoundBtn name="chevronLeft" onClick={() => nav.pop()} />
            <button onClick={() => setPicker('books')} style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, cursor: 'pointer',
              background: 'none', border: 0, fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 18, color: 'var(--nl-navy-900)' }}>
              {chapter} <Icon name="chevronDown" size={16} style={{ color: 'var(--nl-ink-500)' }} />
            </button>
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => setSize(s => Math.max(15, s - 2))} style={{ width: 38, height: 38, borderRadius: 999,
                border: '1px solid var(--nl-border)', background: 'var(--nl-white)', cursor: 'pointer', fontFamily: 'var(--nl-font-serif)',
                fontSize: 13, fontWeight: 600, color: 'var(--nl-navy-800)' }}>A</button>
              <button onClick={() => setSize(s => Math.min(26, s + 2))} style={{ width: 38, height: 38, borderRadius: 999,
                border: '1px solid var(--nl-border)', background: 'var(--nl-white)', cursor: 'pointer', fontFamily: 'var(--nl-font-serif)',
                fontSize: 18, fontWeight: 600, color: 'var(--nl-navy-800)' }}>A</button>
            </div>
          </div>
        </div>

        {/* text */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '26px 26px calc(env(safe-area-inset-bottom, 0px) + 40px)' }}>
          <div className="nl-eyebrow" style={{ marginBottom: 6 }}>World English Bible</div>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 30, color: 'var(--nl-navy-900)', margin: '0 0 20px' }}>{chapter}</h1>

          {!verses && !loadErr && <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>Loading chapter…</p>}
          {loadErr && <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>{loadErr}</p>}

          {verses && (
            <div style={{ fontFamily: 'var(--nl-font-serif)', fontSize: size, lineHeight: 1.75, color: 'var(--nl-navy-900)' }}>
              {verses.map(([n, t]) => {
                const color = hl[n];
                const hasNote = store.verseNotes[`${chapter}:${n}`];
                return (
                  <span key={n} onClick={() => openSheet(n)} style={{ cursor: 'pointer',
                    background: color ? HL[color] : (sel === n ? 'var(--nl-navy-100)' : 'transparent'),
                    borderRadius: 4, padding: color || sel === n ? '1px 2px' : 0, transition: 'background .15s', boxDecorationBreak: 'clone', WebkitBoxDecorationBreak: 'clone' }}>
                    <sup style={{ fontFamily: 'var(--nl-font-sans)', fontSize: size * 0.55, fontWeight: 700,
                      color: 'var(--nl-leaf-700)', marginRight: 4 }}>{n}</sup>
                    {t}
                    {hasNote && <Icon name="note" size={size * 0.7} style={{ color: 'var(--nl-clay-700)', display: 'inline', verticalAlign: 'middle', margin: '0 3px' }} />}
                    {' '}
                  </span>
                );
              })}
            </div>
          )}

          {/* chapter nav */}
          {ref && (
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 36, gap: 12 }}>
              <button disabled={ref.chapter <= 1} onClick={() => go(`${ref.book} ${ref.chapter - 1}`)}
                className="nl-btn nl-btn--ghost" style={{ flex: 1, opacity: ref.chapter <= 1 ? 0.35 : 1, justifyContent: 'center' }}>
                <Icon name="chevronLeft" size={18} /> Previous
              </button>
              <button disabled={ref.chapter >= chapterCount} onClick={() => go(`${ref.book} ${ref.chapter + 1}`)}
                className="nl-btn nl-btn--ghost" style={{ flex: 1, opacity: ref.chapter >= chapterCount ? 0.35 : 1, justifyContent: 'center' }}>
                Next <Icon name="chevronRight" size={18} />
              </button>
            </div>
          )}
        </div>

        {/* book & chapter picker */}
        {picker !== null && (
          <React.Fragment>
            <div onClick={() => setPicker(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(5,31,46,0.35)', zIndex: 70 }} />
            <div style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 71, background: 'var(--nl-white)',
              borderRadius: '22px 22px 0 0', padding: '16px 0 calc(env(safe-area-inset-bottom, 0px) + 16px)',
              boxShadow: 'var(--nl-shadow-xl)', maxHeight: '70%', display: 'flex', flexDirection: 'column' }}>
              <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--nl-ink-200)', margin: '0 auto 12px', flexShrink: 0 }} />
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 20px 12px', flexShrink: 0 }}>
                {picker !== 'books' ? (
                  <button onClick={() => setPicker('books')} style={{ background: 'none', border: 0, cursor: 'pointer', display: 'flex',
                    alignItems: 'center', gap: 4, fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14, color: 'var(--nl-navy-800)' }}>
                    <Icon name="chevronLeft" size={16} /> Books
                  </button>
                ) : <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 18, color: 'var(--nl-navy-900)' }}>Choose a book</div>}
                <button onClick={() => setPicker(null)} style={{ background: 'none', border: 0, cursor: 'pointer', color: 'var(--nl-ink-500)' }}>
                  <Icon name="x" size={20} />
                </button>
              </div>

              <div style={{ overflowY: 'auto', padding: '0 20px' }}>
                {picker === 'books' ? (
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, paddingBottom: 8 }}>
                    {D.BOOKS.map(([b]) => (
                      <button key={b} onClick={() => setPicker(b)} style={{ textAlign: 'left', cursor: 'pointer',
                        background: ref && ref.book === b ? 'var(--nl-navy-50)' : 'var(--nl-ink-50)', border: '1px solid var(--nl-border)',
                        borderRadius: 10, padding: '11px 13px', fontFamily: 'var(--nl-font-sans)', fontSize: 14.5, color: 'var(--nl-navy-900)' }}>
                        {b}
                      </button>
                    ))}
                  </div>
                ) : (
                  <React.Fragment>
                    <div style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 20, color: 'var(--nl-navy-900)', margin: '4px 0 12px' }}>{picker}</div>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8, paddingBottom: 8 }}>
                      {Array.from({ length: (D.BOOKS.find(([b]) => b === picker) || [null, 1])[1] }, (_, i) => i + 1).map(n => (
                        <button key={n} onClick={() => { go(`${picker} ${n}`); setPicker(null); }} style={{ cursor: 'pointer', aspectRatio: '1',
                          background: chapter === `${picker} ${n}` ? 'var(--nl-navy-800)' : 'var(--nl-ink-50)',
                          color: chapter === `${picker} ${n}` ? '#fff' : 'var(--nl-navy-900)',
                          border: '1px solid var(--nl-border)', borderRadius: 10,
                          fontFamily: 'var(--nl-font-sans)', fontWeight: 600, fontSize: 14 }}>{n}</button>
                      ))}
                    </div>
                  </React.Fragment>
                )}
              </div>
            </div>
          </React.Fragment>
        )}

        {/* verse action sheet */}
        {sel !== null && (
          <React.Fragment>
            <div onClick={close} style={{ position: 'fixed', inset: 0, background: 'rgba(5,31,46,0.35)', zIndex: 70 }} />
            <div style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 71, background: 'var(--nl-white)',
              borderRadius: '22px 22px 0 0', padding: '16px 20px calc(env(safe-area-inset-bottom, 0px) + 30px)', boxShadow: 'var(--nl-shadow-xl)' }}>
              <div style={{ width: 40, height: 4, borderRadius: 999, background: 'var(--nl-ink-200)', margin: '0 auto 14px' }} />
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
                <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 13, letterSpacing: '0.08em',
                  textTransform: 'uppercase', color: 'var(--nl-leaf-700)' }}>{chapter}:{sel}</div>
                <button onClick={close} style={{ background: 'none', border: 0, cursor: 'pointer', color: 'var(--nl-ink-500)' }}><Icon name="x" size={20} /></button>
              </div>

              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
                {Object.keys(HL).map(c => {
                  const active = hl[sel] === c;
                  return (
                    <button key={c} onClick={() => store.setHighlight(chapter, sel, active ? null : c)}
                      style={{ width: 40, height: 40, borderRadius: 999, cursor: 'pointer', background: HL[c],
                        border: active ? '2.5px solid var(--nl-navy-800)' : '2px solid rgba(0,0,0,0.06)' }} />
                  );
                })}
                <button onClick={() => store.setHighlight(chapter, sel, null)} style={{ width: 40, height: 40, borderRadius: 999, cursor: 'pointer',
                  background: 'var(--nl-white)', border: '2px dashed var(--nl-border-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--nl-ink-500)' }}>
                  <Icon name="x" size={16} />
                </button>
              </div>

              <textarea value={noteDraft} onChange={e => setNoteDraft(e.target.value)}
                placeholder="Add a note to this verse…" className="nl-textarea"
                style={{ minHeight: 84, resize: 'none', fontSize: 14.5, lineHeight: 1.5, marginBottom: 12 }} />

              <div style={{ display: 'flex', gap: 10 }}>
                <button onClick={() => { store.setVerseNote(`${chapter}:${sel}`, noteDraft); close(); }}
                  className="nl-btn nl-btn--primary" style={{ flex: 1 }}>Save note</button>
                <button onClick={() => {
                  const v = (verses || []).find(x => x[0] === sel);
                  const text = v ? `“${v[1]}” — ${chapter}:${sel} (WEB)` : `${chapter}:${sel}`;
                  if (navigator.share) navigator.share({ text }).catch(() => {});
                  else { navigator.clipboard && navigator.clipboard.writeText(text); alert('Verse copied'); }
                }} className="nl-btn nl-btn--outline" style={{ width: 52, padding: 0 }}><Icon name="share" size={19} /></button>
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
    );
  }

  // ---- Highlights & notes list -------------------------------------------
  function Highlights({ nav, store }) {
    const items = [];
    Object.entries(store.highlights).forEach(([ch, vs]) => Object.entries(vs).forEach(([n, c]) => {
      const verse = (chapterVerses(ch) || []).find(v => String(v[0]) === n);
      items.push({ ref: `${ch}:${n}`, ch, color: c, text: verse ? verse[1] : '', note: store.verseNotes[`${ch}:${n}`] });
    }));
    Object.entries(store.verseNotes).forEach(([key, note]) => {
      if (!items.find(i => i.ref === key)) {
        const [ch, n] = key.split(':'); const verse = (chapterVerses(ch) || []).find(v => String(v[0]) === n);
        items.push({ ref: key, ch, color: null, text: verse ? verse[1] : '', note });
      }
    });
    return (
      <Screen header={{ variant: 'detail', title: 'My Bible', onBack: () => nav.pop() }}>
        <div style={{ padding: '0 20px 16px' }}>
          <h1 style={{ fontFamily: 'var(--nl-font-serif)', fontWeight: 600, fontSize: 28, color: 'var(--nl-navy-900)', margin: 0 }}>Highlights & notes</h1>
        </div>
        <div style={{ padding: '0 20px' }}>
          {items.length === 0 && (
            <div style={{ textAlign: 'center', padding: '50px 20px', color: 'var(--nl-ink-400)' }}>
              <Icon name="highlighter" size={40} style={{ color: 'var(--nl-ink-300)', margin: '0 auto 12px' }} />
              <p className="nl-body" style={{ color: 'var(--nl-ink-500)' }}>Highlight a verse while you read and it’ll show up here.</p>
            </div>
          )}
          {items.map((it, i) => (
            <button key={i} onClick={() => nav.push('reader', { chapter: it.ch })} style={{ display: 'block', width: '100%', textAlign: 'left',
              cursor: 'pointer', background: 'var(--nl-white)', border: '1px solid var(--nl-border)',
              borderLeft: `4px solid ${it.color ? HL[it.color] : 'var(--nl-clay-300)'}`, borderRadius: 12, padding: 16, marginBottom: 10 }}>
              <div style={{ fontFamily: 'var(--nl-font-sans)', fontWeight: 700, fontSize: 12, letterSpacing: '0.06em',
                textTransform: 'uppercase', color: 'var(--nl-leaf-700)', marginBottom: 6 }}>{it.ref}</div>
              <div style={{ fontFamily: 'var(--nl-font-serif)', fontSize: 15.5, lineHeight: 1.5, color: 'var(--nl-navy-900)' }}>
                {it.text ? `“${it.text}”` : 'Open the chapter to see this verse.'}
              </div>
              {it.note && <div style={{ fontFamily: 'var(--nl-font-sans)', fontSize: 13.5, color: 'var(--nl-ink-600)', marginTop: 10,
                paddingTop: 10, borderTop: '1px solid var(--nl-divider)', display: 'flex', gap: 7 }}>
                <Icon name="note" size={15} style={{ color: 'var(--nl-clay-700)', flexShrink: 0, marginTop: 1 }} /> {it.note}</div>}
            </button>
          ))}
        </div>
      </Screen>
    );
  }

  window.NLBible = { Bible, Reader, Highlights };
})();
