// BookEditionReader — the whole book, top to bottom, in the Plain-reading
// tier of the analytical translation. Adapter: fetches /api/editions/plain/
// {abbr} and renders it through DidacheReader, so stitched Bible editions get
// the SAME editorial chrome as every other long-form work in the library
// (kicker, chapter heroes, margin verse numbers, tools bar). Each pericope
// carries a head row with "Full analysis →" into the study workspace.
(function () {

  // plain block markdown → [{v, text}] (strip blockquote marks, bold, italics)
  function parseVerses(md) {
    const paras = [];
    let cur = [];
    for (const raw of md.split('\n')) {
      const l = raw.replace(/^>\s?/, '').trim();
      if (!l) { if (cur.length) { paras.push(cur.join(' ')); cur = []; } continue; }
      cur.push(l);
    }
    if (cur.length) paras.push(cur.join(' '));
    const text = paras.join('\n');
    // verse markers may be single (**5**) or grouped (**25–26**, **9-11**)
    const parts = text.split(/\*\*(\d+(?:\s*[–—-]\s*\d+)?)\*\*/);
    const verses = [];
    // parts: [before, label, seg, label, seg, …]
    for (let i = 1; i < parts.length; i += 2) {
      const clean = (parts[i + 1] || '')
        .replace(/\*\*([^*]+)\*\*/g, '$1')
        .replace(/\*([^*]+)\*/g, '$1')
        .replace(/\n+/g, ' ')
        .replace(/\s{2,}/g, ' ')
        .trim();
      const label = parts[i].replace(/\s+/g, '');
      if (clean) verses.push({ v: parseInt(label, 10), vl: label, text: clean });
    }
    // leading un-numbered text (rare) folds into the first verse
    const lead = parts[0].replace(/\*/g, '').trim();
    if (lead && verses.length) verses[0].text = lead + ' ' + verses[0].text;
    return verses;
  }

  const refOf = p => (p.chapter || '') + (p.v1 ? ':' + p.v1 +
    (p.v2 && p.v2 !== p.v1 ? '–' + p.v2 : '') : '');

  function buildDocMeta(d) {
    const byCh = {};
    d.pericopes.forEach(p => { (byCh[p.chapter] = byCh[p.chapter] || []).push(p); });
    const chapters = Object.keys(byCh).sort((a, b) => a - b).map(chN => {
      const en = [];
      byCh[chN].forEach(p => {
        const vs = parseVerses(p.plain);
        if (vs.length) {
          vs[0] = {
            ...vs[0],
            head: {
              // untitled pericopes show their reference as the heading —
              // never the word "Pericope"
              title: p.title || (d.book_name + ' ' + refOf(p)),
              ref: p.title
                ? d.book_name + ' ' + refOf(p) + (p.derived ? ' · derived' : '')
                : (p.derived ? 'derived' : ''),
              studyId: p.id
            }
          };
        }
        en.push(...vs);
      });
      return {
        n: parseInt(chN, 10),
        title: d.book_name + ' ' + chN,
        section: d.book_name,
        summary: byCh[chN].map(p => p.title).filter(Boolean).join(' · '),
        en
      };
    });
    return {
      id: 'plain-' + d.abbr,
      title: d.book_name,
      subtitle: "Amos's AI Analytical Translation — Plain Reading",
      lede: 'The clean tier of the analytical translation, stitched from ' + d.count +
        ' pericope analyses so the book reads top to bottom. Every pericope opens ' +
        'into its full apparatus — Greek text, word analysis, early-church reception, ' +
        'textual variants.' + (d.missing.length ? ' ' + d.missing.length +
        ' pericopes are not yet retranslated and appear as gaps.' : ''),
      collection: 'The Amos Project',
      collectionKey: null,
      manuscript: (d.bases && d.bases.length ? d.bases.join(' · ') : 'THGNT 2017'),
      edition: 'The Amos Project · analytical translation, plain tier',
      editionNote: 'STITCHED EDITION · ' + d.count + ' PERICOPE ANALYSES · AI DRAFTS PENDING SCHOLAR SIGN-OFF',
      langs: 'English (plain reading)',
      languages: [{ key: 'en', label: 'English', sub: 'Plain reading · analytical translation' }],
      endText: 'End of ' + d.book_name + ' · plain reading edition of The Amos Project analytical translation. Every pericope above opens into its full apparatus.',
      hasStudies: false,   // pericope-level "Full analysis" replaces per-verse hooks
      fullLoaded: true,
      chapters
    };
  }

  function BookEditionReader({ abbr, focusId, onClose, onOpenStudy, onOpenHub, onOpenTestament, onOpenLibrary }) {
    const [st, setSt] = React.useState({ loading: true });
    React.useEffect(() => {
      let on = true;
      setSt({ loading: true });
      Promise.all([
        window.AmosAPI.plainEdition(abbr),
        window.AmosAPI.citations ? window.AmosAPI.citations(abbr).catch(() => null) : null
      ])
        .then(([d, cit]) => {
          if (!on) return;
          const meta = buildDocMeta(d);
          if (cit && cit.chapters) {
            meta.chapters.forEach(ch => { ch.reception = cit.chapters[ch.n] || []; });
            meta.citationsEndpoint = '/api/citations/' + abbr + '?source=trust-ledger';
          }
          setSt({ data: d, meta });
        })
        .catch(e => on && setSt({ error: String(e) }));
      window.scrollTo(0, 0);
      return () => { on = false; };
    }, [abbr]);

    // deep-link: land on the focus pericope's first verse (e.g. from a study's §II)
    React.useEffect(() => {
      if (!st.data || !focusId) return;
      const p = st.data.pericopes.find(x => x.id === focusId);
      if (!p) return;
      const t = setTimeout(() => {
        const el = document.getElementById('ddc-' + p.chapter + '-' + p.v1);
        if (el) el.scrollIntoView({ block: 'center' });
      }, 120);
      return () => clearTimeout(t);
    }, [st.data, focusId]);

    if (st.loading) return React.createElement('div',
      { style: { padding: '90px 0', textAlign: 'center', color: '#8a8375' } },
      'Stitching the book…');
    if (st.error || !st.meta) return React.createElement('div',
      { style: { padding: '60px', textAlign: 'center', color: '#8a8375' } },
      React.createElement('button', {
        onClick: onClose, style: { marginBottom: 16, cursor: 'pointer', font: 'inherit' }
      }, '← Back'),
      React.createElement('div', null, 'Could not load the edition — the content service isn\u2019t reachable.'));

    return React.createElement(DidacheReader, {
      docMeta: { ...st.meta, hereLabel: 'Plain Reading' },
      // the Library crumb (and the end-of-book back button) must land on
      // the Library DETERMINISTICALLY — onClose merely closes this view and
      // would reveal whatever page happens to sit underneath (often the hub).
      onBack: onOpenLibrary || onClose,
      onOpenCollection: () => onOpenHub && onOpenHub(abbr),
      onOpenPericope: null,
      onOpenVaultStudy: (id) => onOpenStudy && onOpenStudy(id),
      // full trail: … › New Testament › {Book} › Plain Reading
      crumbs: [
        onOpenTestament && { label: 'New Testament', onClick: () => onOpenTestament() },
        { label: st.data.book_name, onClick: () => onOpenHub && onOpenHub(abbr) }
      ].filter(Boolean)
    });
  }
  window.BookEditionReader = BookEditionReader;
})();
