// Search — CMD+K modal that searches across all modules and sections
function Search({ onSelectModule, onClose, previewMode = false }) {
  const [query, setQuery] = React.useState('');
  const [results, setResults] = React.useState([]);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    setTimeout(() => inputRef.current?.focus(), 50);
  }, []);

  React.useEffect(() => {
    if (!query.trim()) { setResults([]); return; }
    const q = query.toLowerCase();
    const hits = [];

    (previewMode ? MODULES_DATA.filter(m => m.id === 1) : MODULES_DATA).forEach(mod => {
      // Module title match
      if (mod.title.toLowerCase().includes(q) || mod.subtitle.toLowerCase().includes(q)) {
        hits.push({ type: 'module', mod, section: null, label: mod.title, sub: mod.subtitle, score: 10 });
      }
      // Section matches
      mod.sections.forEach(sec => {
        const titleMatch = sec.title.toLowerCase().includes(q);
        const contentMatch = (sec.content || '').toLowerCase().includes(q);
        const codeMatch = (sec.code?.content || '').toLowerCase().includes(q);
        if (titleMatch || contentMatch || codeMatch) {
          // Extract snippet around match
          let snippet = '';
          if (contentMatch) {
            const idx = (sec.content || '').toLowerCase().indexOf(q);
            snippet = (sec.content || '').slice(Math.max(0, idx - 40), idx + 80).replace(/\n/g, ' ');
          }
          hits.push({
            type: 'section', mod, section: sec,
            label: sec.title, sub: `Module ${mod.num} — ${mod.title}`,
            snippet, score: titleMatch ? 8 : 5
          });
        }
      });
      // Exercise matches
      (mod.exercises || []).forEach((ex, i) => {
        if (ex.title.toLowerCase().includes(q) || ex.description.toLowerCase().includes(q)) {
          hits.push({
            type: 'exercise', mod, section: null, exIdx: i,
            label: ex.title, sub: `Exercise — Module ${mod.num}`,
            snippet: ex.description.slice(0, 100), score: 6
          });
        }
      });
    });

    hits.sort((a, b) => b.score - a.score);
    setResults(hits.slice(0, 12));
  }, [query]);

  function handleSelect(hit) {
    onSelectModule(hit.mod, hit.section?.id || (hit.type === 'exercise' ? 'exercises' : null));
    onClose();
  }

  const accentColor = '#C9A84C';
  const typeIcon = { module: '◈', section: '§', exercise: '⊡' };
  const typeColor = { module: '#C9A84C', section: '#3B82F6', exercise: '#7BB7A8' };

  return (
    <div style={{ position:'fixed', inset:0, zIndex:200, display:'flex', alignItems:'flex-start', justifyContent:'center', paddingTop:80 }}
      onClick={onClose}>
      {/* Backdrop */}
      <div style={{ position:'absolute', inset:0, background:'rgba(0,0,0,0.85)' }} />

      {/* Modal */}
      <div style={{ position:'relative', width:'100%', maxWidth:600, background:'#0a0a0a', border:'1px solid #2a2a2a', zIndex:1 }}
        onClick={e => e.stopPropagation()}>

        {/* Search input */}
        <div style={{ display:'flex', alignItems:'center', gap:12, padding:'14px 18px', borderBottom:'1px solid #1a1a1a' }}>
          <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:14, color:'#444' }}>⌕</span>
          <input ref={inputRef} value={query} onChange={e => setQuery(e.target.value)}
            placeholder={previewMode ? 'Search Module 1…' : 'Search modules, sections, exercises...'}
            style={{ flex:1, background:'none', border:'none', outline:'none',
              fontFamily:'Inter,sans-serif', fontSize:15, color:'#fff',
              caretColor: accentColor }}
            onKeyDown={e => { if (e.key === 'Escape') onClose(); }}
          />
          <kbd style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', border:'1px solid #222', padding:'2px 6px', letterSpacing:'0.1em' }}>ESC</kbd>
        </div>

        {/* Results */}
        {results.length > 0 ? (
          <div style={{ maxHeight:480, overflowY:'auto' }}>
            {results.map((hit, i) => (
              <button key={i} onClick={() => handleSelect(hit)}
                style={{ width:'100%', textAlign:'left', background:'none', border:'none',
                  borderBottom:'1px solid #0d0d0d', padding:'12px 18px',
                  cursor:'pointer', display:'flex', alignItems:'flex-start', gap:12,
                  transition:'background 0.1s' }}
                onMouseEnter={e => e.currentTarget.style.background='#111'}
                onMouseLeave={e => e.currentTarget.style.background='none'}>

                <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:14, color:typeColor[hit.type], flexShrink:0, marginTop:1 }}>
                  {typeIcon[hit.type]}
                </span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:8 }}>
                    <span style={{ fontFamily:'Inter,sans-serif', fontSize:14, color:'#fff', fontWeight:500 }}>
                      {highlight(hit.label, query)}
                    </span>
                    <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', letterSpacing:'0.12em', flexShrink:0, textTransform:'uppercase' }}>
                      {hit.type}
                    </span>
                  </div>
                  <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:10, color:'#444', letterSpacing:'0.12em', marginTop:3 }}>
                    {hit.sub}
                  </div>
                  {hit.snippet && (
                    <div style={{ fontFamily:'Inter,sans-serif', fontSize:12, color:'#555', marginTop:4, lineHeight:1.5,
                      overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                      ...{hit.snippet}...
                    </div>
                  )}
                </div>
              </button>
            ))}
          </div>
        ) : query.trim() ? (
          <div style={{ padding:'32px', textAlign:'center' }}>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:11, color:'#333', letterSpacing:'0.14em', textTransform:'uppercase' }}>No results for "{query}"</div>
          </div>
        ) : (
          <div style={{ padding:'20px 18px' }}>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#333', textTransform:'uppercase', marginBottom:12 }}>Quick navigation</div>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {['agents','RAG','streaming','fine-tuning','prompt caching','cost optimisation'].map(term => (
                <button key={term} onClick={() => setQuery(term)}
                  style={{ fontFamily:'JetBrains Mono,monospace', fontSize:10, letterSpacing:'0.12em',
                    background:'#111', border:'1px solid #222', color:'#666',
                    padding:'5px 10px', cursor:'pointer', textTransform:'lowercase' }}>
                  {term}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Footer */}
        <div style={{ padding:'8px 18px', borderTop:'1px solid #0d0d0d', display:'flex', gap:16 }}>
          {[['↑↓','navigate'],['↵','open'],['ESC','close']].map(([k,l]) => (
            <div key={k} style={{ display:'flex', gap:5, alignItems:'center' }}>
              <kbd style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', border:'1px solid #222', padding:'2px 5px' }}>{k}</kbd>
              <span style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, color:'#333', letterSpacing:'0.1em' }}>{l}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function highlight(text, query) {
  if (!query.trim()) return text;
  const idx = text.toLowerCase().indexOf(query.toLowerCase());
  if (idx === -1) return text;
  return (
    <>
      {text.slice(0, idx)}
      <mark style={{ background:'#C9A84C33', color:'#C9A84C', borderRadius:2 }}>{text.slice(idx, idx + query.length)}</mark>
      {text.slice(idx + query.length)}
    </>
  );
}

Object.assign(window, { Search });
