// SemanticSearchPage — sidebar → Search the corpus.
// Optimized for usability: a big focused input, scope chips, starter prompts,
// recent searches, and a results stream grouped by kind. Every result clicks
// through to the unified StudyView (passages) or to a profile page (voices /
// library texts) so the user never lands on a dead end.

function SemanticSearchPage({
  onBack, onOpenPericope, onOpenDoc, onOpenCollection, onOpenArticle, onOpenReaction,
  initialQuery,
  signedIn, onOpenLanguageModal, onOpenSignIn,
  onOpenUserMenu, userMenuOpen, onCloseUserMenu, onSignOut
}) {
  const I = window.useI18n();
  const [query, setQuery] = React.useState(initialQuery || '');
  const [scope, setScope] = React.useState('all');
  const inputRef = React.useRef(null);

  // Auto-focus on page open. Pressing "/" anywhere refocuses too.
  React.useEffect(() => {
    if (inputRef.current) inputRef.current.focus();
    const onKey = (e) => {
      if (e.key === '/' && document.activeElement !== inputRef.current) {
        e.preventDefault();
        if (inputRef.current) inputRef.current.focus();
      } else if (e.key === 'Escape' && document.activeElement === inputRef.current) {
        setQuery('');
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const SCOPES = [
    { id: 'all',       label: 'All' },
    { id: 'passages',  label: 'Passages' },
    { id: 'voices',    label: 'Early-church voices' },
    { id: 'library',   label: 'Library texts' },
    { id: 'topics',    label: 'Topics & terms' }
  ];

  // Starter prompts surface what the corpus is good at — helps a new user
  // discover real connections instead of guessing.
  const STARTERS = [
    'divine patience',
    'election in Romans 9',
    'the potter’s wheel',
    'Pharaoh’s hardening',
    'remnant theology',
    'Origen on foreknowledge',
    'Wisdom 15 vessels',
    'the Two Ways tradition',
    'pre-Nicene on free will',
    'Jacob and Esau covenant'
  ];

  // Mock recent searches — shown only when signed in.
  const RECENT = [
    { q: 'divine patience',    when: 'yesterday',   hits: 47 },
    { q: 'Romans 9 election',  when: '3 days ago',  hits: 124 },
    { q: 'Origen on Pharaoh',  when: '1 week ago',  hits: 18 },
    { q: 'Two Ways · 1QS',     when: '2 weeks ago', hits: 31 }
  ];

  // Demo result generator. In production this hits a semantic-search API;
  // here we return a curated set so each starter prompt feels plausible.
  const buildResults = (q, sc) => {
    if (!q || q.length < 2) return [];
    const all = [];
    if (sc === 'all' || sc === 'passages') {
      // Passages → open the unified StudyView at that pericope.
      all.push(
        { kind: 'passage', icon: 'book', title: 'Romans 9:1–33',
          snippet: 'Vessels of wrath fitted (κατηρτισμένα — passive, agent ambiguous) for destruction; vessels of mercy he prepared beforehand (προητοίμασεν — active, God explicit). The asymmetry is deliberate.',
          meta: 'Paul · Romans · Pre-Nicene patristic reception available',
          relevance: 96,
          openHint: 'Open passage →',
          onClick: () => onOpenPericope && onOpenPericope({ book:'rom', chap:9, v1:1, v2:33, state:'sealed' })
        },
        { kind: 'passage', icon: 'book', title: 'Galatians 3:10–14',
          snippet: 'Christ redeemed us from the curse of the law, having become a curse for us — buying someone out of the slave market (ἐξηγόρασεν).',
          meta: 'Paul · Galatians · 2 traditions traced',
          relevance: 81,
          openHint: 'Open passage →',
          onClick: () => onOpenPericope && onOpenPericope({ book:'gal', chap:3, v1:10, v2:14, state:'sealed' })
        },
        { kind: 'passage', icon: 'book', title: 'Wisdom of Solomon 12:20–22',
          snippet: 'God’s patience (μακροθυμία) toward the Egyptians as time given for repentance — the direct lexical parallel Paul invokes at Rom 9:22.',
          meta: 'Wisdom of Solomon · Septuagint · Library parallel',
          relevance: 78,
          openHint: 'Open passage →',
          onClick: () => onOpenPericope && onOpenPericope({ book:'wis', chap:12, v1:20, v2:22, state:'c' })
        }
      );
    }
    if (sc === 'all' || sc === 'voices') {
      // Voices → open as a long-form Amos-style article. The voice gets
      // its own reading surface (AmosArticleReader), not the pericope study.
      all.push(
        { kind: 'voice', icon: 'feather', title: 'Origen on foreknowledge ≠ causation',
          snippet: '“God foresees future things because they will be, not the other way around — divine knowledge does not introduce necessity into events, but apprehends them as they will occur.”',
          meta: 'Origen of Alexandria · Comm. Rom. VII · cited at Rom 9:11',
          relevance: 92,
          openHint: 'Open article →',
          onClick: () => onOpenArticle && onOpenArticle('letter-from-amos')
        },
        { kind: 'voice', icon: 'feather', title: 'Irenaeus: corporate election, not individualized',
          snippet: 'Israel chosen as a people — “firstfruits of the nations.” God’s sovereignty works by persuasion, not coercion.',
          meta: 'Irenaeus of Lyon · Adv. Haer. IV.28 · cited at Rom 9 and Rom 11',
          relevance: 85,
          openHint: 'Open article →',
          onClick: () => onOpenArticle && onOpenArticle('prayer-in-the-world-jesus-inherited')
        }
      );
    }
    if (sc === 'all' || sc === 'library') {
      // Library texts → open the Preterocanonical Library collection page
      // (or, when more granular library readers exist, jump to the text).
      all.push(
        { kind: 'library', icon: 'scroll', title: '1QS III.13–IV.26 · Community Rule',
          snippet: 'The Maskil is to teach the sons of light concerning two spirits God has placed in man — the spirit of truth and the spirit of falsehood.',
          meta: 'Qumran · Two-spirits doctrine · strong resonance with Romans 9',
          relevance: 74,
          openHint: 'Open in Qumran collection →',
          onClick: () => onOpenCollection && onOpenCollection('qumran')
        },
        { kind: 'library', icon: 'scroll', title: 'Jubilees 19:13–14',
          snippet: 'Jacob and Esau differentiated in the womb, Jacob designated bearer of the covenant — pre-Pauline articulation of κατ’ ἐκλογὴν πρόθεσις.',
          meta: 'Jubilees · Preterocanonical · strong resonance with Rom 9:11',
          relevance: 71,
          openHint: 'Open in Preterocanonical Library →',
          onClick: () => onOpenCollection && onOpenCollection('parabiblical')
        }
      );
    }
    if (sc === 'all' || sc === 'topics') {
      // Topics → open as long-form Amos articles in AmosArticleReader.
      all.push(
        { kind: 'topic', icon: 'hash', title: 'Predestination vs. foreknowledge — the Augustinian inversion',
          snippet: 'How the Augustinian-Calvinist reading of Romans 9 inverts the pre-Nicene consensus on κατ’ ἐκλογὴν πρόθεσις. Six passages, five voices.',
          meta: 'Topic · 6 passages · 5 voices · Theological tensions discussed',
          relevance: 66,
          openHint: 'Open article →',
          onClick: () => onOpenArticle && onOpenArticle('letter-from-amos')
        },
        { kind: 'topic', icon: 'hash', title: 'μακροθυμία — divine patience as temporal posture',
          snippet: 'The semantic range of μακροθυμία across Wisdom, Sirach, 4 Ezra, and Paul. Argues against eternal-decree readings of Rom 9:22.',
          meta: 'Term study · 12 passages · 4 voices',
          relevance: 58,
          openHint: 'Open article →',
          onClick: () => onOpenArticle && onOpenArticle('prayer-in-the-world-jesus-inherited')
        }
      );
    }
    // Sort by relevance, descending.
    return all.sort((a, b) => (b.relevance || 0) - (a.relevance || 0));
  };

  const results = buildResults(query, scope);
  const groupedCount = (k) => results.filter(r => r.kind === k).length;

  // ── Page ───────────────────────────────────────────────────
  return React.createElement('div', { className: 'amos-main' },
    // Topbar (matches other pages)
    React.createElement('div', { className: 'amos-topbar' },
      React.createElement('button', {
        className: 'amos-sidebar-toggle',
        onClick: () => window.dispatchEvent(new CustomEvent('amos:toggle-sidebar')),
        title: '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('a', { className: 'crumb-link', onClick: onBack }, I.t('crumbs.library')),
        React.createElement('span', { className: 'sep' }, '›'),
        React.createElement('span', { className: 'here' }, 'Search')
      ),
      React.createElement('div', { className: 'amos-topbar-right' },
        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('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))
        ),
        React.createElement('span', { className: 'topbar-sep' }),
        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 — search input is the primary affordance.
    React.createElement('section', { className: 'sem-hero' },
      React.createElement('h1', { className: 'sem-h1' }, 'Search the corpus'),
      React.createElement('p', { className: 'sem-sub' },
        'Find passages, voices, library texts, and topics across canonical scripture, the pre-Nicene fathers, and the preterocanonical library.'
      ),
      React.createElement('div', { className: 'sem-input-wrap' },
        React.createElement('span', { className: 'sem-input-icon' }, window.I.search(20)),
        React.createElement('input', {
          ref: inputRef,
          className: 'sem-input',
          type: 'text',
          placeholder: 'e.g. divine patience, election, Origen on Pharaoh, the potter’s wheel…',
          value: query,
          onChange: (e) => setQuery(e.target.value),
          autoFocus: true
        }),
        query && React.createElement('button', {
          className: 'sem-clear',
          onClick: () => setQuery(''),
          title: 'Clear'
        }, '×'),
        !query && React.createElement('span', { className: 'sem-input-hint' },
          React.createElement('kbd', null, '/'), ' to focus'
        )
      ),
      // Scope chips
      React.createElement('div', { className: 'sem-scopes' },
        SCOPES.map(s => React.createElement('button', {
          key: s.id,
          className: 'sem-scope ' + (scope === s.id ? 'on' : ''),
          onClick: () => setScope(s.id)
        },
          s.label,
          query && s.id !== 'all' && React.createElement('span', { className: 'sem-scope-count' }, groupedCount(s.id.replace(/s$/, '')))
        ))
      )
    ),

    // Default state: starter prompts + recent searches
    !query && React.createElement('section', { className: 'sem-defaults' },
      React.createElement('div', { className: 'sem-default-block' },
        React.createElement('h3', { className: 'sem-default-head' }, 'Try'),
        React.createElement('div', { className: 'sem-starters' },
          STARTERS.map(s => React.createElement('button', {
            key: s,
            className: 'sem-starter',
            onClick: () => setQuery(s)
          }, s))
        )
      ),
      signedIn && React.createElement('div', { className: 'sem-default-block' },
        React.createElement('h3', { className: 'sem-default-head' }, 'Recent searches'),
        React.createElement('ul', { className: 'sem-recent' },
          RECENT.map((r, i) => React.createElement('li', {
            key: i,
            className: 'sem-recent-item',
            onClick: () => setQuery(r.q)
          },
            React.createElement('span', { className: 'sem-recent-ico' }, window.I.history ? window.I.history(14) : '↻'),
            React.createElement('span', { className: 'sem-recent-q' }, r.q),
            React.createElement('span', { className: 'sem-recent-hits' }, r.hits + ' hits'),
            React.createElement('span', { className: 'sem-recent-when' }, r.when)
          ))
        )
      )
    ),

    // Results
    query && React.createElement('section', { className: 'sem-results' },
      React.createElement('div', { className: 'sem-results-head' },
        React.createElement('span', { className: 'sem-results-count' },
          results.length === 0 ? 'No results' : results.length + ' result' + (results.length === 1 ? '' : 's'),
          ' for ',
          React.createElement('strong', null, '"' + query + '"')
        ),
        results.length > 0 && React.createElement('button', {
          className: 'sem-save-search',
          onClick: () => {},
          title: 'Save this search to your commonplace book'
        }, '+ Save search')
      ),
      results.length === 0 && React.createElement('div', { className: 'sem-empty' },
        React.createElement('p', null,
          'No matches yet. Try a different phrase, or remove the scope filter to broaden across all kinds.'
        )
      ),
      results.map((r, i) => React.createElement('article', {
        key: i,
        className: 'sem-result kind-' + r.kind,
        onClick: r.onClick || (() => {})
      },
        React.createElement('div', { className: 'sem-result-icon' },
          window.I[r.icon] ? window.I[r.icon](16) : ''
        ),
        React.createElement('div', { className: 'sem-result-body' },
          React.createElement('div', { className: 'sem-result-meta-top' },
            React.createElement('span', { className: 'sem-result-kind' }, r.kind),
            r.relevance && React.createElement('span', { className: 'sem-result-relevance' }, r.relevance + '% match')
          ),
          React.createElement('h3', { className: 'sem-result-title' }, r.title),
          React.createElement('p', { className: 'sem-result-snippet' }, r.snippet),
          React.createElement('div', { className: 'sem-result-meta' }, r.meta),
          r.openHint && React.createElement('div', { className: 'sem-result-open-hint' }, r.openHint)
        ),
        React.createElement('span', { className: 'sem-result-arrow' },
          window.I.arrowRight ? window.I.arrowRight(14) : '→'
        )
      ))
    )
  );
}

Object.assign(window, { SemanticSearchPage });
