// AI-Men · 성경 읽기 (멘토 탭 세 번째 세그먼트)
// 개역개정 전체 성경 — 구약 39권(bible/ot.json) + 신약 27권(bible/nt.json).
// Cross-script refs: Icon, Brand, MentorTabSwitch, BottomTabs resolve at render.

const { useState: buseState, useEffect: buseEffect, useRef: buseRef, useMemo: buseMemo } = React;

const BibleStore = {
  KEY: 'aimen.bible.v1',
  get() { try { return JSON.parse(localStorage.getItem(this.KEY)) || { read: {} }; } catch (e) { return { read: {} }; } },
  save(d) { try { localStorage.setItem(this.KEY, JSON.stringify(d)); } catch (e) {} },
  key(t, b, c) { return `${t}-${b}-${c}`; },
  isRead(t, b, c) { return !!this.get().read[this.key(t, b, c)]; },
  toggleRead(t, b, c) {
    const d = this.get(); const k = this.key(t, b, c);
    if (d.read[k]) delete d.read[k]; else d.read[k] = 1;
    this.save(d); return !!d.read[k];
  },
  bookReadCount(t, b) { const d = this.get(); const pre = `${t}-${b}-`; return Object.keys(d.read).filter(k => k.startsWith(pre)).length; },
  setLast(t, b, c) { const d = this.get(); d.last = { t, b, c }; this.save(d); },
  getLast() { return this.get().last || null; },
};
window.BibleStore = BibleStore;

window.__bibleCache = window.__bibleCache || {};

function highlight(text, q) {
  if (!q) return text;
  const idx = text.indexOf(q);
  if (idx < 0) return text;
  const out = []; let i = 0;
  let pos = text.indexOf(q, i);
  while (pos >= 0) {
    if (pos > i) out.push(text.slice(i, pos));
    out.push(<mark key={pos}>{q}</mark>);
    i = pos + q.length;
    pos = text.indexOf(q, i);
  }
  if (i < text.length) out.push(text.slice(i));
  return out;
}

function BibleScreen({ onList, onCourse, onTab }) {
  const [test, setTest] = buseState('ot');
  const [data, setData] = buseState({ ot: window.__bibleCache.ot || null, nt: window.__bibleCache.nt || null });
  const [loading, setLoading] = buseState(false);
  const [err, setErr] = buseState(false);
  const [view, setView] = buseState('home');     // home | chapters | reader
  const [bookIdx, setBookIdx] = buseState(0);
  const [chap, setChap] = buseState(1);
  const [query, setQuery] = buseState('');
  const [target, setTarget] = buseState(null);
  const [, force] = buseState(0);
  const versesRef = buseRef(null);

  // load active testament json on demand
  buseEffect(() => {
    if (data[test]) { setErr(false); return; }
    setLoading(true); setErr(false);
    fetch(`bible/${test}.json`).then(r => r.json()).then(j => {
      window.__bibleCache[test] = j;
      setData(d => ({ ...d, [test]: j }));
      setLoading(false);
    }).catch(() => { setErr(true); setLoading(false); });
  }, [test]);

  buseEffect(() => {
    if (view !== 'reader') return;
    const content = versesRef.current && versesRef.current.closest('.content');
    if (!content) return;
    if (target && versesRef.current) {
      const el = versesRef.current.querySelector(`[data-v="${target}"]`);
      if (el) content.scrollTop = el.offsetTop - 70; else content.scrollTop = 0;
    } else content.scrollTop = 0;
  }, [view, bookIdx, chap, target]);

  const cur = data[test];
  const books = cur ? cur.books : [];

  function switchTest(t) { setTest(t); setView('home'); setQuery(''); setTarget(null); }
  function openChapters(i) { setBookIdx(i); setView('chapters'); }
  function openReader(i, c, tv) { setBookIdx(i); setChap(c); setTarget(tv || null); BibleStore.setLast(test, books[i].n, c); setView('reader'); }
  function markRead() { BibleStore.toggleRead(test, books[bookIdx].n, chap); force(x => x + 1); }

  const results = buseMemo(() => {
    const q = query.trim();
    if (!q || !cur || q.length < 2) return null;
    const out = [];
    for (let bi = 0; bi < books.length; bi++) {
      const bk = books[bi];
      for (let ci = 0; ci < bk.ch.length; ci++) {
        const verses = bk.ch[ci];
        for (let vi = 0; vi < verses.length; vi++) {
          if (verses[vi] && verses[vi].indexOf(q) >= 0) {
            out.push({ bi, c: ci + 1, v: vi + 1, text: verses[vi], book: bk.abbr });
            if (out.length >= 100) return out;
          }
        }
      }
    }
    return out;
  }, [query, cur]);

  const TESTNAME = test === 'ot' ? '구약' : '신약';

  // ===== Reader view =====
  if (view === 'reader' && cur) {
    const bk = books[bookIdx];
    const verses = bk.ch[chap - 1] || [];
    const isRead = BibleStore.isRead(test, bk.n, chap);
    const prevAvail = chap > 1 || bookIdx > 0;
    const nextAvail = chap < bk.ch.length || bookIdx < books.length - 1;
    function goPrev() { if (chap > 1) openReader(bookIdx, chap - 1); else if (bookIdx > 0) openReader(bookIdx - 1, books[bookIdx - 1].ch.length); }
    function goNext() { if (chap < bk.ch.length) openReader(bookIdx, chap + 1); else if (bookIdx < books.length - 1) openReader(bookIdx + 1, 1); }
    return (
      <>
        <div className="appbar">
          <button className="iconbtn" aria-label="Back" onClick={() => { setTarget(null); setView('chapters'); }}><Icon name="chev-left" /></button>
          <div className="appbar-title">{bk.name} {chap}장</div>
          <div style={{ width: 36 }} />
        </div>
        <div className="content">
          <div className="bib-reader-head"><span className="bib-reader-book">{TESTNAME} · 개역개정</span></div>
          <div className="bib-reader-title">{bk.name} {chap}장</div>
          <div className="bib-verses" ref={versesRef}>
            {verses.map((v, i) => v ? (
              <div key={i} className={`bib-verse ${target === i + 1 ? 'hit' : ''}`} data-v={i + 1}>
                <span className="bv-num">{i + 1}</span>
                <span className="bv-text">{target && target === i + 1 ? highlight(v, query.trim()) : v}</span>
              </div>
            ) : null)}
          </div>
          <button className={`bib-read-toggle ${isRead ? 'done' : ''}`} onClick={markRead}>
            {isRead ? <>✓ 읽음 표시됨</> : <>이 장 읽음으로 표시</>}
          </button>
          <div className="bib-reader-nav">
            <button disabled={!prevAvail} onClick={goPrev}><Icon name="chev-left" size={16} stroke={2.2} /> 이전 장</button>
            <button disabled={!nextAvail} onClick={goNext}>다음 장 <Icon name="chev-right" size={16} stroke={2.2} /></button>
          </div>
        </div>
      </>
    );
  }

  // ===== Chapters view =====
  if (view === 'chapters' && cur) {
    const bk = books[bookIdx];
    const last = BibleStore.getLast();
    return (
      <>
        <div className="appbar">
          <button className="iconbtn" aria-label="Back" onClick={() => setView('home')}><Icon name="chev-left" /></button>
          <div className="appbar-title">{bk.name}</div>
          <div style={{ width: 36 }} />
        </div>
        <div className="content">
          <div className="bib-section-label">{bk.ch.length}개 장 · 읽은 장 {BibleStore.bookReadCount(test, bk.n)}</div>
          <div className="bib-ch-grid">
            {bk.ch.map((_, i) => {
              const c = i + 1;
              const read = BibleStore.isRead(test, bk.n, c);
              const isLast = last && last.t === test && last.b === bk.n && last.c === c;
              return <button key={c} className={`bib-ch ${read ? 'read' : ''} ${isLast ? 'last' : ''}`} onClick={() => openReader(bookIdx, c)}>{c}</button>;
            })}
          </div>
        </div>
      </>
    );
  }

  // ===== Home view =====
  const last = BibleStore.getLast();
  const lastBook = last && cur && last.t === test ? books.find(b => b.n === last.b) : null;
  const lastBookIdx = lastBook ? books.indexOf(lastBook) : -1;

  return (
    <>
      <div className="appbar">
        <button className="iconbtn" aria-label="Back" onClick={() => onTab && onTab('home')}><Icon name="chev-left" /></button>
        <Brand />
        <div style={{ width: 36 }} />
      </div>
      <div className="content">
        <window.MentorTabSwitch active="bible" onList={onList} onCourse={onCourse} onBible={() => {}} />

        <div className="bib-test-toggle">
          <button className={`bib-tt ot ${test === 'ot' ? 'on' : ''}`} onClick={() => switchTest('ot')}>
            <Icon name="bookmark" size={15} stroke={2.2} /><span>구약</span><em className="bib-tt-count">39권</em>
          </button>
          <button className={`bib-tt nt ${test === 'nt' ? 'on' : ''}`} onClick={() => switchTest('nt')}>
            <Icon name="bible" size={15} stroke={2.2} /><span>신약</span><em className="bib-tt-count">27권</em>
          </button>
        </div>

        {loading && <div className="bib-loading"><div className="bl-spin" /><div className="bl-text">{TESTNAME} 성경을 불러오는 중…</div></div>}
        {err && !loading && <div className="bib-empty"><div className="be-emoji">📖</div><div className="be-title">성경을 불러오지 못했어요</div><div className="be-text">잠시 후 다시 시도해 주세요.</div></div>}

        {cur && !loading && (
          <>
            <div className="bib-search">
              <span className="bs-icon"><Icon name="search" size={18} /></span>
              <input type="text" inputMode="search" placeholder={`${TESTNAME} 구절 검색 (예: 사랑, 믿음)`} value={query} onChange={e => setQuery(e.target.value)} />
              {query && <button className="bs-clear" onClick={() => setQuery('')}><Icon name="x" size={13} stroke={2.5} /></button>}
            </div>

            {results ? (
              <>
                <div className="bib-results-meta">{results.length >= 100 ? '100개 이상' : `${results.length}개`} 결과{results.length >= 100 ? ' (상위 100개)' : ''}</div>
                {results.length === 0
                  ? <div className="bib-empty"><div className="be-emoji">🔍</div><div className="be-text">검색 결과가 없어요.</div></div>
                  : <div className="bib-results">
                      {results.map((r, i) => (
                        <button key={i} className="bib-result" onClick={() => openReader(r.bi, r.c, r.v)}>
                          <div className="br-ref2">{r.book} {r.c}:{r.v}</div>
                          <div className="br-text">{highlight(r.text, query.trim())}</div>
                        </button>
                      ))}
                    </div>}
              </>
            ) : (
              <>
                {lastBook && (
                  <button className="bib-resume" onClick={() => openReader(lastBookIdx, last.c)}>
                    <span className="br-icon"><Icon name="bookmark" size={20} /></span>
                    <span className="br-body"><span className="br-label">이어 읽기</span><span className="br-ref">{lastBook.name} {last.c}장</span></span>
                    <span className="br-go"><Icon name="chev-right" size={20} stroke={2.4} /></span>
                  </button>
                )}
                <div className="bib-section-label">{TESTNAME} {books.length}권 · 개역개정</div>
                <div className="bib-book-grid">
                  {books.map((b, i) => {
                    const rc = BibleStore.bookReadCount(test, b.n);
                    return (
                      <button key={b.n} className={`bib-book ${rc > 0 ? 'started' : ''}`} onClick={() => openChapters(i)}>
                        {rc > 0 && <span className="bb-dot" />}
                        <span className="bb-abbr">{b.abbr}</span>
                        <span className="bb-ch">{b.ch.length}장</span>
                      </button>
                    );
                  })}
                </div>
              </>
            )}
          </>
        )}
      </div>
    </>
  );
}
window.BibleScreen = BibleScreen;
