// SPDX-FileCopyrightText: 2026 Andrew Oberstar <andrew@ajoberstar.org>
// SPDX-License-Identifier: AGPL-3.0-only

const input = document.querySelector("input[type='search']");
const list = document.getElementById("search-results");
let active = -1;
let timer;

document.addEventListener("keydown", (e) => {
  const target = e.target;
  const isTyping = target.tagName == "INPUT"
        || target.tagName == "TEXTAREA"
        || target.isContentEditable;
  if (!isTyping && e.key == "/") {
    e.preventDefault();
    input.focus();
    input.select();
  }
});

input.addEventListener("input", (e) => {
  clearTimeout(timer);
  const q = input.value.trim();
  if (!q) {
    hide();
    return;
  }
  const search = () => fetch(`/api/search?q=${encodeURIComponent(q)}&page_size=10`)
        .then(r => r.json())
        .then(render);
  timer = setTimeout(search, 250);
});

input.addEventListener("keydown", (e) => {
  const items = list.querySelectorAll("li");
  if (e.key == "ArrowDown") {
    active = (active + 1) % items.length;
    highlight(items);
  } else if (e.key == "ArrowUp") {
    active = (active - 1 + items.length) % items.length;
    highlight(items);
  } else if (e.key == "Enter" && active >= 0) {
    e.preventDefault();
    items[active].querySelector("a").click();
  } else if (e.key == "Escape") {
    hide();
    input.focus();
  }
});

function render(results) {
  active = -1;
  list.innerHTML = results.map(r => `<li class="search-result"><span class="kind ${r.kind}">${r.kind}</span> <a href="${r.url}">${r.description}</a></li>`).join("");
  list.hidden = results.length === 0;
}

function hide() {
  list.hidden = true;
  active = -1;
}

function highlight(items) {
  items.forEach((item, i) => {
    item.classList.toggle("active", i === active);
  });
  if (active >= 0) {
    items[active].scrollIntoView({ block: "nearest" });
  }
}
