// The manual's search — over the generated index, no server, no library.
(function () {
  const field = document.getElementById('search');
  const box = document.getElementById('results');
  if (!field || !box || !window.MANUAL_INDEX) { return; }

  function score(entry, words) {
    let total = 0;
    const title = entry.title.toLowerCase();
    const text = (entry.text || '').toLowerCase();
    for (const word of words) {
      if (title === word) { total += 100; }
      else if (title.startsWith(word)) { total += 40; }
      else if (title.includes(word)) { total += 20; }
      else if (text.includes(word)) { total += 5; }
      else { return 0; }   // every word has to land somewhere
    }
    return total;
  }

  function render(query) {
    const words = query.toLowerCase().split(/\s+/).filter(Boolean);
    if (!words.length) { box.hidden = true; box.innerHTML = ''; return; }
    const hits = window.MANUAL_INDEX
      .map(entry => ({ entry, s: score(entry, words) }))
      .filter(hit => hit.s > 0)
      .sort((a, b) => b.s - a.s)
      .slice(0, 12);
    box.innerHTML = hits.map(hit =>
      '<a href="' + hit.entry.url + '">' + hit.entry.title +
      '<span class="kind">' + hit.entry.kind + '</span></a>').join('');
    box.hidden = hits.length === 0;
  }

  field.addEventListener('input', () => render(field.value));
  field.addEventListener('keydown', event => {
    if (event.key === 'Escape') { field.value = ''; render(''); }
    if (event.key === 'Enter') {
      const first = box.querySelector('a');
      if (first) { location.href = first.getAttribute('href'); }
    }
  });
  document.addEventListener('click', event => {
    if (!box.contains(event.target) && event.target !== field) { box.hidden = true; }
  });

  // A deep link opens its example — arriving at a command should show everything.
  if (location.hash) {
    const target = document.querySelector(location.hash + ' details');
    if (target) { target.open = true; }
  }
})();