// LibraryMainV2 — reframed main view.
//
// Key differences from v1:
//   • Pericope input is the hero (replaces stats block).
//   • Resolves into a 3-action branch; "Retrieve" opens reader, "Commission"
//     opens the Availability Grid modal.
//   • CoverageMap sits above the rails: the whole canon as one picture.
//   • Modes band is reframed: B/C/D as consumer modes + Mode A partner panel.
//   • Corpus labels renamed: Preterocanonical, Zadokite Settlement, etc.
//   • Editorial tier split from completeness tier (new filter chip).
//   • Seal badges appear on doc cards.

function LibraryMainV2({ onOpenDoc, onOpenStudy, onOpenPericope, onCommission, onCommissionBook, onOpenBiblica, onOpenCollection, onOpenVaultStudy, onOpenBook, onOpenTestament, signedIn, onOpenLanguageModal, onOpenSignIn, onOpenUserMenu, userMenuOpen, onCloseUserMenu, onSignOut }) {
  const COLLECTION_PAGE_KEYS = ['patristic','parabiblical','greek','hebrew','latin','qumran','vernacular'];
  const I = window.useI18n();
  const { TRADITIONS, DOCS } = window.LIBRARY_DATA;
  const STUDIES = (window.ANALYTICAL_STUDIES && window.ANALYTICAL_STUDIES.STUDIES) || [];

  const [view, setView] = React.useState('rails');
  const [tradFilter, setTradFilter] = React.useState(null);
  const [langFilter, setLangFilter] = React.useState(null);
  const [tierFilter, setTierFilter] = React.useState(null);
  const [editorialFilter, setEditorialFilter] = React.useState(null);
  const [resolved, setResolved] = React.useState(null);

  // Rename overrides for traditions — v2 editorial voice
  const LABEL_OVERRIDES = {
    patristic:    { name: 'Pre-Nicene Fathers',     sub: 'Irenaeus, Clement, Origen, Tertullian — the generation that hands the apostolic deposit on.' },
    parabiblical: { name: 'Preterocanonical Library', sub: 'Enoch, Jubilees, the Testaments, the Odes, the Nag Hammadi cache — what the canon grew up alongside.' },
    greek:        { name: 'Greek New Testament',    sub: 'TAGNT, THGNT, SBLGNT — critical editions with full morphological tagging and apparatus.' },
    hebrew:       { name: 'Hebrew Scriptures',      sub: 'Masoretic Text with Aramaic witnesses, Targums, morphological tagging.' },
    latin:        { name: 'Septuagint & Vulgate',   sub: 'LXX, Peshitta, Old Latin, Jerome — the ancient translations that shape the western tradition.' },
    qumran:       { name: 'Zadokite Settlement · Dead Sea Scrolls', sub: 'Sectarian writings, pesharim, variant scriptures from the caves above Khirbet Qumran.' },
    vernacular:   { name: 'Vernacular Reference Bibles', sub: 'Modern translations for cross-reference — English, Spanish, Catalan, Portuguese.' },
  };

  const filtered = DOCS.filter(d =>
    (!tradFilter || d.tradition===tradFilter) &&
    (!langFilter || d.langs.includes(langFilter)) &&
    (!tierFilter || d.tier===tierFilter)
  );

  const byTrad = (tkey) => DOCS.filter(d=>d.tradition===tkey);

  const RailHead = ({ t }) => {
    const over = LABEL_OVERRIDES[t.key] || {};
    const isNonCanonical = COLLECTION_PAGE_KEYS.includes(t.key);
    return React.createElement('div', { className:'amos-rail-head' },
      React.createElement('span', { className:`amos-rail-tag trad-${t.class}-bg` }, t.tag + ' · ' + (over.name || t.name).toUpperCase()),
      React.createElement('span', { className:'amos-rail-title' }, over.name || t.name),
      React.createElement('span', { className:'amos-rail-sub' }, over.sub || t.sub),
      React.createElement('span', {
        className:'amos-rail-more',
        onClick: isNonCanonical && onOpenCollection ? (e) => { e.stopPropagation(); onOpenCollection(t.key); } : undefined,
        style: isNonCanonical ? { cursor: 'pointer' } : undefined,
        title: isNonCanonical ? 'Open collection page' : undefined
      }, t.docs + ' documents', window.I.arrowRight(13))
    );
  };

  const handleResolve = (ref) => setResolved(ref);

  return React.createElement('div', { className:'amos-main' },
    // ── Topbar ────────────────────────────────
    React.createElement('div', { className:'amos-topbar' },
      // Sidebar toggle — ALWAYS visible on the far left of the topbar
      React.createElement('button', {
        className: 'amos-sidebar-toggle',
        onClick: () => window.dispatchEvent(new CustomEvent('amos:toggle-sidebar')),
        title: 'Toggle sidebar  ([)',
        'aria-label': 'Toggle sidebar'
      },
        React.createElement('svg', { width:16, height:16, viewBox:'0 0 24 24', fill:'none', stroke:'currentColor', strokeWidth:'2', strokeLinecap:'round', strokeLinejoin:'round' },
          React.createElement('rect', { x:'3', y:'4', width:'18', height:'16', rx:'2' }),
          React.createElement('line', { x1:'9', y1:'4', x2:'9', y2:'20' })
        )
      ),
      React.createElement('div', { className:'amos-crumbs' },
        React.createElement('span', null, 'The Amos Project'),
        React.createElement('span', { className:'sep' }, '›'),
        React.createElement('span', null, I.t('crumbs.library')),
        React.createElement('span', { className:'sep' }, '›'),
        React.createElement('span', { className:'here' }, I.t('crumbs.all_docs'))
      ),
      React.createElement('div', { className:'amos-topbar-right' },
        React.createElement('button', { className:'amos-icon-btn', title:'Filters' }, window.I.sliders(16)),
        window.NotificationsBell ? React.createElement(window.NotificationsBell, null) : React.createElement('button', { className:'amos-icon-btn', title:'Notifications' }, window.I.bell(16)),
        window.WalletChip && React.createElement(window.WalletChip, null),

        React.createElement('div', { className:'amos-sc-pair' },
          React.createElement(window.CiteButton, { compact:true, refFor: () => ({
            kind:'library',
            title:'The Amos Project',
            subtitle:'An open, scholarly library of early Christian writings',
            edition:'The Amos Project, editorial catalog',
            editor:'World Mission Media',
            year:2026,
            url:'https://worldmission.media/',
            description:'Critical editions of the pre‑Nicene, parabiblical, Qumran, and vernacular corpora.'
          }) }),
          React.createElement(window.ShareButton, { compact:true, refFor: () => ({
            kind:'library',
            title:'The Amos Project',
            subtitle:'An open, scholarly library of early Christian writings',
            edition:'The Amos Project',
            editor:'World Mission Media',
            year:2026,
            url:'https://worldmission.media/',
            description:'Critical editions of the early Christian corpus — freely licensed under CC BY 4.0.'
          }) })
        ),

        // Language pill
        React.createElement('button', {
          className:'amos-pill lang',
          onClick: onOpenLanguageModal,
          title: I.getLangObj().native
        },
          React.createElement('span', { className:'code' }, I.getLang()),
          React.createElement('span', { className:'chev' }, window.I.chevronDown(14))
        ),

        // Visual divider between language and identity
        React.createElement('span', { className:'topbar-sep' }),

        // User area — sign-in pill (logged-out) or avatar pill (logged-in)
        signedIn
          ? React.createElement('div', { className:'amos-userpill-wrap' },
              React.createElement('button', {
                className:'amos-pill avatar',
                onClick: onOpenUserMenu
              },
                React.createElement('span', { className:'av' }, 'JR'),
                React.createElement('span', { className:'chev' }, window.I.chevronDown(14))
              ),
              React.createElement(window.UserMenu, {
                open: !!userMenuOpen,
                onClose: onCloseUserMenu,
                onSignOut
              })
            )
          : React.createElement('button', {
              className:'amos-pill signin',
              onClick: onOpenSignIn
            }, I.t('topbar.sign_in'))
      )
    ),

    // ── Hero: reference input ────────────────
    React.createElement('section', { className:'amos-hero', style: { paddingBottom: 0 } },
      React.createElement('div', { className:'amos-hero-top' },
        React.createElement('div', null,
          React.createElement('h1', null, I.t('hero.title_a') + ' ', React.createElement('em', null, I.t('hero.title_b'))),
          React.createElement('div', { className:'sub' }, I.t('hero.sub'))
        )
      )
    ),
    React.createElement(window.PericopeInput, {
      onResolve: handleResolve,
      onFocusChange: () => {}
    }),
    resolved && React.createElement(window.PericopeBranch, {
      pref: resolved,   // 'ref' is reserved by React — must not be used as a prop name
      onRetrieve: (r) => onOpenPericope && onOpenPericope(r),
      onCommission: (r) => onCommission && onCommission(r),
      onCrossCorpus: (r) => onOpenPericope && onOpenPericope(r),
      onDismiss: () => setResolved(null)
    }),

    // ── Reception Record — authoritative platform stats (vault source of truth) ──
    window.ReceptionRecord && React.createElement(window.ReceptionRecord, { variant: 'in-library' }),

    // ── Reader's bookshelf door — the canon on one screen (the coverage map
    //    below stays the workbench lens of the same 27 books) ──
    onOpenTestament && React.createElement('div', {
      style: { display: 'flex', justifyContent: 'flex-end', margin: '18px 0 -6px' }
    },
      React.createElement('button', {
        onClick: onOpenTestament,
        style: {
          border: '1px solid rgba(27,42,51,.16)', background: '#fff',
          borderRadius: '999px', padding: '9px 18px', font: 'inherit',
          fontSize: '13.5px', fontWeight: 600, color: '#13232c', cursor: 'pointer'
        }
      }, 'Browse the New Testament as a library →')
    ),

    // ── Coverage Map ─────────────────────────
    React.createElement(window.CoverageMap, {
      // Real cells carry true chapter:verse coordinates; only the legacy demo
      // cells fall back to the old pericope-index-as-chapter behavior.
      onOpenPericope: (p) => onOpenPericope && onOpenPericope({ book: p.book, chap: (p.chap != null ? p.chap : p.idx), v1: p.v1, v2: p.v2, state: p.state, seals: p.seals, lumo: p.lumo, lang: p.lang }),
      onCommission:   (p) => onCommission   && onCommission({ book: p.book, chap: (p.chap != null ? p.chap : p.idx), state: p.state }),
      onOpenBiblica:  (p, lang) => onOpenBiblica && onOpenBiblica(p, lang),
      onOpenVaultStudy,
      onOpenBook,
      onOpenCollection
    }),

    // ── Linguist-review trust note ───────────
    // Sits between the heat-map and the toolbar so the filters/sort that
    // follow visually apply only to the tradition rails further down.
    view==='rails' && React.createElement('div', { className: 'amos-review-note' },
      React.createElement('p', { style: { margin: 0, fontSize: '13px', color: 'var(--tan-cyan-700)', lineHeight: 1.55 } },
        React.createElement('strong', null, 'Some passages have been reviewed by linguists.'),
        ' When you see a check mark on a translation, a credentialed reviewer from one of our partner agencies has signed off on the rendering: ',
        React.createElement('span', { style: { display: 'inline-flex', gap: '4px', verticalAlign: 'middle', margin: '0 4px' } },
          ['bib', 'bec', 'ubs', 'wyc', 'abs'].map(c =>
            React.createElement(window.SealBadge, { key: c, code: c, sm: true })
          )
        ),
        '. ',
        React.createElement('a', {
          href: '#',
          onClick: (e) => { e.preventDefault(); },
          style: { color: 'var(--tan-cyan-600)', textDecoration: 'none', fontWeight: 600 }
        }, 'See reviewed pericopes →')
      )
    ),

    // ── Toolbar ──────────────────────────────
    React.createElement('div', { className:'amos-toolbar' },
      React.createElement('button', { className:'amos-chip '+(!tradFilter?'on':''), onClick:()=>setTradFilter(null) }, I.t('filter.all_trad')),
      ...TRADITIONS.map(t => {
        const over = LABEL_OVERRIDES[t.key] || {};
        return React.createElement('button', {
          key: t.key,
          className: 'amos-chip ' + (tradFilter===t.key?'on':''),
          onClick: () => setTradFilter(t.key)
        },
          React.createElement('span', { style: { width:8, height:8, borderRadius:4, background: ({patristic:'#b8443a',parabiblical:'#8b6d9e',greek:'#5b7aa8',hebrew:'#7a9579',latin:'#d4a24c',qumran:'#8a7b58',vernacular:'#26828F'})[t.key] }}),
          (over.name || t.name).replace(/ · .*/,'')
        );
      }),
      React.createElement('div', { className:'amos-divider-v' }),
      React.createElement('button', { className:'amos-chip' }, window.I.filter(13), I.t('filter.language')+' · ', langFilter||I.t('filter.any'), window.I.chevronDown(13)),
      React.createElement('button', { className:'amos-chip' }, window.I.filter(13), I.t('filter.completeness')+' · ', tierFilter||I.t('filter.any'), window.I.chevronDown(13)),
      React.createElement('button', {
        className: 'amos-chip tier-toggle ' + (editorialFilter ? 'on' : ''),
        onClick: () => setEditorialFilter(editorialFilter ? null : 'sealed')
      },
        window.I.filter(13), I.t('filter.seal')+' · ', editorialFilter || I.t('filter.any'), window.I.chevronDown(13)
      ),
      React.createElement('button', { className:'amos-chip' }, window.I.filter(13), I.t('filter.era'), window.I.chevronDown(13)),
      React.createElement('button', { className:'amos-sort' }, window.I.sort(13), I.t('filter.sort_trad')),
      React.createElement('div', { className:'amos-view-switch' },
        React.createElement('button', { className:view==='rails'?'on':'', onClick:()=>setView('rails'), title:'Rails' }, window.I.layers(14)),
        React.createElement('button', { className:view==='grid'?'on':'', onClick:()=>setView('grid'), title:'Grid' }, window.I.grid(14)),
        React.createElement('button', { className:view==='list'?'on':'', onClick:()=>setView('list'), title:'List' }, window.I.list(14))
      )
    ),

    // ── Modes band v2 — REMOVED ──────────────
    // The "Two ways to engage · Read any passage / Study it deeply" band
    // was redundant: every heat-map cell now opens the unified StudyView,
    // so the user discovers all the depths by clicking. The component is
    // still in the codebase if we want it back for marketing later.
    // (Replaced with `false &&` so the surrounding array stays valid.)
    false && React.createElement('div'),

    // ── Analytical studies rail (rails only) ──
    // ── Deep-studies rail — REMOVED ──────────
    // The "Passages studied in depth" tile rail used to surface the four
    // authored studies on the home. Redundant now that any heat-map cell
    // opens the unified StudyView. The data still lives in
    // window.ANALYTICAL_STUDIES.STUDIES — only the home-page rail goes away.
    false && React.createElement('div'),

    // ── Body ─────────────────────────────────
    view==='rails' && React.createElement('div', null,
      TRADITIONS.filter(t => !tradFilter || t.key===tradFilter).map(t => {
        const docs = byTrad(t.key);
        if (!docs.length) return null;
        return React.createElement('section', { key: t.key, className: 'amos-rail' },
          React.createElement(RailHead, { t }),
          React.createElement('div', { className: 'amos-rail-scroll' },
            docs.map(d => React.createElement(window.DocCardV2, { key: d.id, d, onOpen: onOpenDoc, seals: getSealsFor(d), onCommissionBook }))
          )
        );
      })
    ),
    // Grid: group by tradition when no tradition filter; flat grid when one is picked
    view==='grid' && (tradFilter
      ? React.createElement('div', { className:'amos-grid' },
          filtered.map(d => React.createElement(window.DocCardV2, { key:d.id, d, onOpen: onOpenDoc, seals: getSealsFor(d), onCommissionBook }))
        )
      : React.createElement('div', null,
          TRADITIONS.map(t => {
            const docs = byTrad(t.key);
            if (!docs.length) return null;
            return React.createElement('section', { key: t.key, className: 'amos-grid-group' },
              React.createElement(RailHead, { t }),
              React.createElement('div', { className:'amos-grid' },
                docs.map(d => React.createElement(window.DocCardV2, { key: d.id, d, onOpen: onOpenDoc, seals: getSealsFor(d), onCommissionBook }))
              )
            );
          })
        )
    ),

    // List: group by tradition when no tradition filter
    view==='list' && (tradFilter
      ? React.createElement('div', { className:'amos-list' },
          React.createElement('div', { className:'amos-list-head' },
            React.createElement('div', null, ''),
            React.createElement('div', null, 'Title'),
            React.createElement('div', null, 'Collection'),
            React.createElement('div', { style:{textAlign:'right'} }, 'Words'),
            React.createElement('div', null, 'Languages'),
            React.createElement('div', null, 'Seals'),
            React.createElement('div', null, '')
          ),
          filtered.map(d => React.createElement(window.DocListRowV2, { key:d.id, d, onOpen: onOpenDoc, seals: getSealsFor(d), onCommissionBook }))
        )
      : React.createElement('div', null,
          TRADITIONS.map(t => {
            const docs = byTrad(t.key);
            if (!docs.length) return null;
            return React.createElement('section', { key: t.key, className: 'amos-list-group' },
              React.createElement(RailHead, { t }),
              React.createElement('div', { className:'amos-list' },
                React.createElement('div', { className:'amos-list-head' },
                  React.createElement('div', null, ''),
                  React.createElement('div', null, 'Title'),
                  React.createElement('div', null, 'Collection'),
                  React.createElement('div', { style:{textAlign:'right'} }, 'Words'),
                  React.createElement('div', null, 'Languages'),
                  React.createElement('div', null, 'Seals'),
                  React.createElement('div', null, '')
                ),
                docs.map(d => React.createElement(window.DocListRowV2, { key: d.id, d, onOpen: onOpenDoc, seals: getSealsFor(d), onCommissionBook }))
              )
            );
          })
        )
    ),
    React.createElement(window.Footer, null)
  );
}

// Deterministic seal assignment for a doc (demo).
function getSealsFor(d) {
  const CODES = ['bib','bec','ubs','wyc','abs'];
  let h = 2166136261;
  const s = d.id || d.title || '';
  for (let i=0;i<s.length;i++){ h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
  const r1 = ((h >>> 0) % 100) / 100;
  const r2 = (((h*31) >>> 0) % 100) / 100;
  if (r1 > 0.6) return [];
  const n = r1 < 0.15 ? 2 : 1;
  const seals = [];
  for (let i=0;i<n;i++) seals.push(CODES[Math.floor((r1 + i*0.31 + r2*0.17) * 100) % CODES.length]);
  return Array.from(new Set(seals));
}

Object.assign(window, { LibraryMainV2, getSealsFor });
